Capture data from FORM using jQuery/Ajax/JSON - asp.net

I have a few textboxes on a form and when the user submits I want to capture the data and insert it into a database.
Here is what my code looks like
// Called just before the form is submitted.
beforeSubmit: function(data)
{
var item = $("[id$='item']");
var category = $("[id$='category']");
var record = $("[id$='record']");
var json = "{'ItemName':'" + escape(item.val()) +
"','CategoryID':'" + category.val() + "','RecordID':'" + record.val() + "'}";
//This page is where data is to be retrieved and processed.
var ajaxPage = "DataProcessor.aspx?Save=1";
var options =
{
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response)
{
alert("success: " + response);
},
error: function(msg)
{
alert("failed: " + msg);
}
};
//Execute the Ajax call and get a response.
var returnText = $.ajax(options).responseText;
if (returnText == 1) {
record.html(returnText);
$("#divMsg").html("<font color=blue>Record saved successfully.</font>");
}
else
{
record.html(returnText);
$("#divMsg").html("<font color=red>Record not saved successfully.</font>");
}
// $("#data").html("<font color=blue>Data sent to the server :</font> <br />" + $.param(data));
},
Here is what data is sent to the server: if I uncomment the following line.
// $("#data").html("<font color=blue>Data sent to the server :</font> <br />" + $.param(data));
__VIEWSTATE=%2FwEPDwULLTE4ODM1ODM4NDFkZOFEQfA7cHuTisEwOQmIaj1nYR23&__EVENTVALIDATION=%2FwEWDwLuksaHBgLniKOABAKV8o75BgLlosbxAgKUjpHvCALf9YLVCgLCtfnhAQKyqcC9BQL357nNAQLW9%2FeuDQKvpuq2CALyveCRDwKgoPWXDAKhwImNCwKiwImN &day_fi=12&month_fi=12&year_fi=1234&lastFour_fi=777&countryPrefix_fi=1&areaCode_fi=555-555&phoneNumber_fi=5555&email_fi=nisardotnet%40gmail.com&username=nisarkhan&password=123456&retypePassword=123456

Nisardotnet - are you working in C#? You've got way too much going on here. You can cut down your code by half using web methods - also, get rid of viewstate - you don't need it (remove the form from the page)
If your working in C# let me know and I can help.
Rob
****APPEND****
Ok - I built a simple "grab input values and update DB" thing - it's on my site here.
Give me a shout if you've got any questions.
Rob
****APPEND****
Ok, so in your class file you could have
internal static void updateDB(String values)
{
// do something with 'values'
}
Then in your aspx page you can call it like so...
[WebMethod]
public static void updateDB(String values)
{
yourClass.updateDB(values);
}
That should work.

You should be able to pull it all out of the Request.Form.

Related

How to display Array from console log to asp.net mvc

Hello guys i been searching for 2 days now on how to display the data from object that are seen in the picture.
here is my code in Ajax
$.ajax({
url: url,
data: { systemID: selectid },
success: function (jsonData) {
console.log(jsonData);
if (jsonData != null) {
console.log("enterif");
$('#sapNumber').val(jsonData.SapNumber);
$('#careerLevel').val(jsonData.SapLevel);
$('#seatsReleased').val(jsonData.SeatsReleased);
$('#noOfSR').val(jsonData.NumberOfSR);
$('#revenueLost').val(jsonData.RevenueLost);
$('#releaseDate').val(jsonData.ReleaseDate);
$('#fte').val(jsonData.FTE);
console.log("enterif2");
$('#releaseType').val(jsonData.ReleaseType);
$('#category').val(jsonData.Category);
$('#ctsID').val(jsonData.CTSID);
$('#agileHours').val(jsonData.AgileHours);
$('#fTERedeployment').val(jsonData.FTERedeployment);
$('#contractName').val(jsonData.ContractName);
$('#masterContractName').val(jsonData.MasterContractNumber);
$('#fromWBS').val(jsonData.FromWBS);
$('#toWBS').val(jsonData.ToWBS);
$('#comment').val(jsonData.Comment);
}
}

Razor #Html.ActionLink not getting passed control value correctly

I am new to Razor. I am making good progress on this project but have hit a major road block with something that would seem to be easy. I have read a lot of posts about how to pass the value of a control as a parameter to a controller in order to redirect to a new view. The problem is that I either get the value passed to the controller but can't redirect OR I redirect and the parameter is not passed.
This is my latest attempt. I was hoping to pass the return of GetSelectedEmail to the controller (the value of "selectedEmail"). I can see that the Javascript is getting the correct value and the controller is being called, but the value is always NULL.
#Html.ActionLink("Get Scoring Report...", "History", "Student", null, new { onclick = "return GetSelectedEmail();" });
<select id="selectedEmail" name="align">
#foreach( var s in Model.Students )
{
<option id=#s.Email>#s.Email</option>
}
</select>
function GetSelectedEmail() {
var str = "new {email=" + $("#selectedEmail").val() + "}";
return str;
}
The controller...
public ActionResult History(string email, string sort)
{
string localEmail="";
if ( email == null || email == "" )
localEmail = AccountProfile.CurrentUser.UserName;
...
I have also tried to call the controller with Ajax like below. The controller does get the "selectedEmail" parameter but the page never redirects. I just does nothing. I tried both having the action link with the link parameters or not (show below).
#Html.ActionLink("Get Scoring Report...", "", "", null, new { onclick = "return GetSelectedEmail();" });
<select id="selectedEmail" name="align">
#foreach( var s in Model.Students )
{
<option id=#s.Email>#s.Email</option>
}
</select>
function GetSelectedEmail() {
$.ajax({
url: '/Student/History',
data: { email: $("#selectedEmail").val(), sort: "CaseID" },
type: 'POST',
dataType: 'json',
});
return true;
}
Any ideas?
Your first approach is not actually doing the redirection. ( also it calls a different method, which i am assuming a copy paste mistake)
Your current code is not passing the values because it is a link and when it is clicked, it is supposed to navigate to that url, which is exactly what it is doing.
I just changed the code to use unobtrusive javascript. Replaced the onclick with an id for the link
#Html.ActionLink("Get Scoring Report", "History", "Student", null, new { id="score" });
and when the click happens on this link, read the value of the select element and navigate to the second action method by setting the location.href property value
$(function () {
$("#score").click(function(e) {
e.preventDefault(); // Stop the normal redirection
var url = $(this).attr("href"); //Get the url to action method
url += "?email=" + $("#selectedEmail").val(); //append querystrings
window.location.href = url; // redirect to that url
});
});
For what I needed the solution was simple.
Show Student Scores
<select id="selectedEmail" name="align">
#foreach( var s in Model.Students )
{
<option id="#s.Email">#s.LastName,#s.FirstName</option>
}
</select>
And the Javascript magic...
function GetScoreHistory() {
var emailVal = $('#selectedEmail').find('option:selected').attr('id');
var url = '#Url.Action("History", "Student")';
url += "?email=" + escape(emailVal);
window.location.href = url;
}
The controller was called exactly how I needed it to be called.

Not able to retrieve if the parameter starts with zero when passing from jquery to my webmethod

My Problem looks really strange, I am calling an Autocomplete.asmx web method from jQuery. Thew first time the first parameter, 0, is passing, and the second time the zero is getting replaced, instead of 0, any other numbers are getting displayed.
Aspx:
function SearchText() {
$('#<%=txtphoneno.ClientID%>').autocomplete({
source: function (request, response) {
Search();
}
});
}
//-->loadtop 5 jobs
function Search() {
var callid = $('#<%= txtphoneno.ClientID%>').val().toString();
// alert(callid);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../HttpHandler/Autocomplete.asmx/GetCallername",
data: "{'callerid':" + callid + "}",
dataType: "json",
success: function (data) {
//response(data.d);
// alert(data.d);
$('#<%=txtname .ClientID %>').removeClass('text-label');
$('#<%=txtname .ClientID %>').addClass('lbls');
$('#<%=txtnote .ClientID %>').removeClass('text-label');
$('#<%=txtnote .ClientID %>').addClass('lbls');
document.getElementById('<%=txtname .ClientID %>').value = data.d[0];
document.getElementById('<%=txtnote .ClientID %>').value = data.d[1];
if (data.d != 'User Doesnt Exist') {
var param = $('#<%= txtphoneno.ClientID%>').val();
$("#<%=IframeJobHistory.ClientID%>").show();
LoadHistoryDetails(param);
}
else {
// $("#<%=IframeJobHistory.ClientID%>").hide();
}
},
error: function (result) {
// alert("Error");
}
});
}
** CS Code AutoComplete.Asmx**
[WebMethod ]
public string [] GetCallername(String callerid)
{
..............................
return CallerDetails;
}
}
In the String callerid, the first time when the user enters 0 I am getting back 0, but second time when the user enters any number I am getting the number but the Zero disappears.
If i use any other number,apart from zero things are working fine.
instead of using zero try to use -1
Sorry , I don't know what you missed , But I know the simple one
solution for your issue .
Just add this code for dynamically add 0 if the first value is not zero, Otherwise it's diaplayed your default value
Put break point and check
[WebMethod ]
public string [] GetCallername(string callerid)
{
string Filteredcallerid = !string.IsNullOrEmpty(callerid) ? callerid.Substring(0, 1) : "";
callerid = Filteredcallerid != "0" ? "0" + callerid : callerid;
return CallerDetails;
}

Uploading to Azure

I'm having an issue trying to directly upload a file to azure blob storage. I am using ajax calls to send post requests to an ashx handler to upload a blob in chunks. The issue I am running into is the handler isn't receiving the filechunk being sent from the ajax post.
I can see the page is receiving the post correctly from looking at the request in firebug,
-----------------------------265001916915724 Content-Disposition: form-data; >name="Slice"; filename="blob" Content-Type: application/octet-stream
I noticed the input stream on the handler has the filechunk, including additional bytes from the request. I tryed to read only the filechunk's size from the inputstream, however this resulted in an corrupt file.
I got the inspiration from http://code.msdn.microsoft.com/windowsazure/Silverlight-Azure-Blob-3b773e26 , I simply converted it from MVC3 to using standard aspx.
Here is the call using ajax to send the file chunk to the aspx page,
var sendFile = function (blockLength) {
var start = 0,
end = Math.min(blockLength, uploader.file.size),
incrimentalIdentifier = 1,
retryCount = 0,
sendNextChunk, fileChunk;
uploader.displayStatusMessage();
sendNextChunk = function () {
fileChunk = new FormData();
uploader.renderProgress(incrimentalIdentifier);
if (uploader.file.slice) {
fileChunk.append('Slice', uploader.file.slice(start, end));
}
else if (uploader.file.webkitSlice) {
fileChunk.append('Slice', uploader.file.webkitSlice(start, end));
}
else if (uploader.file.mozSlice) {
fileChunk.append('Slice', uploader.file.mozSlice(start, end));
}
else {
uploader.displayLabel(operationType.UNSUPPORTED_BROWSER);
return;
}
var testcode = 'http://localhost:56307/handler1.ashx?create=0&blockid=' + incrimentalIdentifier + '&filename=' + uploader.file.name + '&totalBlocks=' + uploader.totalBlocks;
jqxhr = $.ajax({
async: true,
url: testcode,
data: fileChunk,
contentType: false,
processData:false,
dataType: 'text json',
type: 'POST',
error: function (request, error) {
if (error !== 'abort' && retryCount < maxRetries) {
++retryCount;
setTimeout(sendNextChunk, retryAfterSeconds * 1000);
}
if (error === 'abort') {
uploader.displayLabel(operationType.CANCELLED);
uploader.resetControls();
uploader = null;
}
else {
if (retryCount === maxRetries) {
uploader.uploadError(request.responseText);
uploader.resetControls();
uploader = null;
}
else {
uploader.displayLabel(operationType.RESUME_UPLOAD);
}
}
return;
},
success: function (notice) {
if (notice.error || notice.isLastBlock) {
uploader.renderProgress(uploader.totalBlocks + 1);
uploader.displayStatusMessage(notice.message);
uploader.resetControls();
uploader = null;
return;
}
++incrimentalIdentifier;
start = (incrimentalIdentifier - 1) * blockLength;
end = Math.min(incrimentalIdentifier * blockLength, uploader.file.size);
retryCount = 0;
sendNextChunk();
}
});
};
Thanks so much for anything that can help me out.
is it ASPX on purpose? in http://localhost:56307/handler1.ashx?create=0&blockid?
Turns out on my webform, the input file tag was missing the enctype="multipart/form-data" attribute.

Persisting json data in jstree through postback via asp:hiddenfield

I've been pouring over this for hours and I've yet to make much headway so I was hoping one of the wonderful denizens of SO could help me out. Here's the problem...
I'm implementing a tree via the jstree plugin for jQuery. I'm pulling the data with which I populate the tree programatically from our webapp via json dumped into an asp:HiddenField, basically like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(Items);
json = json.ToLower();
data.Value = json;
Then, the tree pulls the json from the hidden field to build itself. This works perfectly fine up until I try to persist data for which nodes are selected/opened. To simplify my problem I've hardcoded some json data into the tree and attempted to use the cookie plugin to persist the tree state data. This does not work for whatever reason. I've seen other issues where people need to load the plugins in a specific order, etc, this did not solve my issue. I tried the same setup with html_data and it works perfectly. With this working persistence I converted the cookie plugin to persist the data in a different asp:hiddenfield (we can't use cookies for this type of thing in our application.)
essentially the cookie operations are identical, it just saves the array of nodes as the value of a hidden field. This works with the html_data, still not with the json and I have yet to be able to put my finger on where it's failing.
This is the jQuery.cookie.js replacement:
jQuery.persist = function(name, value) {
if (typeof value != 'undefined') { // name and value given, set persist
if (value === null) {
value = '';
}
jQuery('#' + name).attr('value', value);
} else { // only name given, get value
var persistValue = null;
persistValue = jQuery('#' + name).attr('value');
return persistValue;
}
};
The jstree.cookie.js code is identical save for a few variable name changes.
And this is my tree:
$(function() {
$("#demo1").jstree({
"json_data": {
"data" : [
{
"data" : "A node",
"children" : [ "Child 1", "Child 2" ]
},
{
"attr": { "id": "li.node.id" },
"data" : {
"title": "li.node.id",
"attr": { "href": "#" }
},
"children": ["Child 1", "Child 2"]
}
]
},
"persistence": {
"save_opened": "<%= open.ClientID %>",
"save_selected": "<%= select.ClientID %>",
"auto_save": true
},
"plugins": ["themes", "ui", "persistence", "json_data"]
});
});
The data -is- being stored appropriately in the hiddenfields, the problem occurs on a postback, it does not reopen the nodes. Any help would be greatly appreciated.
After looking through this some more, I just wanted to explain that it appears to me that the issue is that the tree has not yet been built from the JSON_data when the persistence operations are being attempted. Is there any way to postpone these actions until after the tree is fully loaded?
If anyone is still attempting to perform the same type of operation on a jsTree version 3.0+ there is an easier way to accomplish the same type of functionality, without editing any of the jsTree's core JavaScript, and without relying on the "state" plugin (Version 1.0 - "Persistence"):
var jsTreeControl = $("#jsTreeControl");
//Can be a "asp:HiddenField"
var stateJSONControl = $("#stateJSONControl");
var url = "exampleURL";
jsTreeControl.jstree({
'core': {
"data": function (node, cb) {
var thisVar = this;
//On the initial load, if the "state" already exists in the hidden value
//then simply use that rather than make a AJAX call
if (stateJSONControl.val() !== "" && node.id === "#") {
cb.call(thisVar, { d: JSON.parse(stateJSONControl.val()) });
}
else {
$.ajax({
type: "POST",
url: url,
async: true,
success: function (json) {
cb.call(thisVar, json);
},
contentType: "application/json; charset=utf-8",
dataType: "json"
}).responseText;
}
}
}
});
//If the user changes the jsTree, save the full JSON of the jsTree into the hidden value,
//this will then be restored on postback by the "data" function in the jsTree decleration
jsTreeControl.on("changed.jstree", function (e, data) {
if (typeof (data.node) != 'undefined') {
stateJSONControl.val(JSON.stringify(jsTreeControl.jstree(true).get_json()));
}
});
This code will create a jsTree and save it's "state" into a hidden value, then upon postback when the jsTree is recreated, it will use its old "state" restored from the "HiddenField" rather than make a new AJAX call and lose the expansions/selections that the user has made.
Got it working properly with JSON data. I had to edit the "reopen" and "reselect" functions inside jstree itself.
Here's the new functioning reopen function for anyone who needs it.
reopen: function(is_callback) {
var _this = this,
done = true,
current = [],
remaining = [];
if (!is_callback) { this.data.core.reopen = false; this.data.core.refreshing = true; }
if (this.data.core.to_open.length) {
$.each(this.data.core.to_open, function(i, val) {
val = val.replace(/^#/, "")
if (val == "#") { return true; }
if ($(("li[id=" + val + "]")).length && $(("li[id=" + val + "]")).is(".jstree-closed")) { current.push($(("li[id=" + val + "]"))); }
else { remaining.push(val); }
});
if (current.length) {
this.data.core.to_open = remaining;
$.each(current, function(i, val) {
_this.open_node(val, function() { _this.reopen(true); }, true);
});
done = false;
}
}
if (done) {
// TODO: find a more elegant approach to syncronizing returning requests
if (this.data.core.reopen) { clearTimeout(this.data.core.reopen); }
this.data.core.reopen = setTimeout(function() { _this.__callback({}, _this); }, 50);
this.data.core.refreshing = false;
}
},
The problem was that it was trying to find the element by a custom attribute. It was just pushing these strings into the array to search when it was expecting node objects. Using this line
if ($(("li[id=" + val + "]")).length && $(("li[id=" + val + "]")).is(".jstree-closed")) { current.push($(("li[id=" + val + "]"))); }
instead of
if ($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
was all it took. Using a similar process I was able to persist the selected nodes this way as well.
Hope this is of help to someone.

Resources