jQuery 1.5 Pass strings and an object to a .NET page method
I have simplified my code to just passing the array but still am not having any luck
When I step through the code and get to the point of the ajax requestjsonText contains:
[{"UserId":"8"},{"UserId":"9"},{"UserId":"5"},{"UserId":"13"},{"UserId":"6"},{"UserId":"11"}]
and
jsonTextSerialized contains:
"[{\"UserId\":\"8\"},{\"UserId\":\"9\"},{\"UserId\":\"5\"},{\"UserId\":\"13\"},{\"UserId\":\"6\"},{\"UserId\":\"11\"}]"
function GetUserSchedules() {
var jsonText = $.toJSON(arrParams);
var js开发者_StackOverflow社区onTextSerialized = Sys.Serialization.JavaScriptSerializer.serialize(jsonText);
$.ajax({
type: "POST",
url: "/myurl/jquery.aspx/GenerateUserSchedules",
data: "{'data':'" + jsonTextSerialized + "'}",
contentType: "application/json",
dataType: "json",
success: function () { alert('Made It!'); },
error: function (result) { alert(Failed: ' + result.responseText);
});
My code behind has
[Serializable]
public class User
{
public int UserId { get; set; }
}
[System.Web.Script.Services.ScriptMethod]
[System.Web.Services.WebMethod]
public static void GenerateUserSchedules(User[] data)
{
//do stuff
}
The responseText is:
"There was an error processing the request.","StackTrace":"","ExceptionType":""}What am I doing wrong?
MY SOLUTION WITH YOUR HELP:
Thank you all for your efforts. I can't express how grateful for all your input. I am embarassed to admit it, but I had been stuck on this for days.
I see from all your answers that there are various ways to approach this. I like the JSON.stringify solution best for two reasons:
- It removes the danger of inadvertant typos when I add parameters to the ajax request.
- According to Oleg, it is a more efficient way to serialize the data objects
So here is how I decided to resolve the issue.
<script type="text/javascript">
var startDate;
var endDate;
var ddlViewSelectedItem;
var ddlViewSelectedValue;
var ddlOrgSelectedValue;
var arrUsers= [];
$(document).ready(function () {
ddlViewSelectedItem = $('#<%=ddlView.ClientID %> option:selected').text();
ddlViewSelectedValue = $('#<%=ddlView.ClientID %> option:selected').val();
ddlOrgSelectedValue = $('#<%=ddlOrganization.ClientID %> option:selected').val();
$.when(GetStartDate(), GetEndDate()) //these populate strt and end dates
.then(function () {
GetUserIDs(); // populates arrUsers
GetUserSchedules();
})
.fail(function () {
failureAlertMsg();
})
});
// Here I use JSON.stringify because it simplifies adding params. No messy single and/or double quote confusion. I love this. Must include json2.js from https://github.com/douglascrockford/JSON-js/blob/master/json2.js
function GetUserSchedules() {
var jsonTextStringified = JSON.stringify({ data: arrParams, startDate: startDate, endDate: endDate, ddlViewSelectedItem: ddlViewSelectedItem, ddlViewSelectedValue: ddlViewSelectedValue, ddlOrgSelectedValue: ddlOrgSelectedValue });
$.ajax({
type: "POST",
url: "/myurl/jquery.aspx/GenerateUserSchedules", // this is a call to a pagemethod, not a webservice, so .aspx is correct
data: jsonTextStringified,
contentType: "application/json",
dataType: "json",
success: function () { alert('Sweet! Made It!'); }
,
error: function (result) { alert('Failed!: ' + result.responseText); }
});
}
Code behind:
[Serializable]
public class User
{
public string UserId { get; set; }
}
[System.Web.Script.Services.ScriptMethod]
[System.Web.Services.WebMethod]
public static void GenerateUserSchedules(User[] data, string startDate, string endDate, string ddlViewSelectedItem, string ddlViewSelectedValue, string ddlOrgSelectedValue)
{
//do cool stuff and eventually send data back
}
Thank you again for all your help
Look at the close answer here, here or here. Many people made the same errors.
- In the initialization of JavaScript objects you can use both quotes and double quotes, but in the JSON data only double quotes are permitted.
- You should no time make JSON serialization manual like
{"{'startDate':'" + startDate + "', ...
and not use old$.toJSON
jQuery plugin. The best way is to use JSON.stringify function from the json2.js. The most current version of the web browsers support the function in the native code, so it work very quickly.
One more thing which look strange is the path "/myurl/jquery.aspx/GenerateUserSchedules" instead of "/myurl/jquery.asmx/GenerateUserSchedules" (asmx instead of aspx).
In your case you should use
data: JSON.stringify({
startDate: startDate,
endDate: endDate,
ddlViewSelectedItem: ddlViewSelectedItem,
ddlViewSelectedValue: ddlViewSelectedValue,
ddlOrgSelectedValue: ddlOrgSelectedValue
})
in case of usage of type: "POST"
and
data: {
startDate: JSON.stringify(startDate),
endDate: JSON.stringify(endDate),
ddlViewSelectedItem: JSON.stringify(ddlViewSelectedItem),
ddlViewSelectedValue: JSON.stringify(ddlViewSelectedValue),
ddlOrgSelectedValue: JSON.stringify(ddlOrgSelectedValue)
}
if you decide to use type: "GET"
.
It is important to send data for all input parameters of the web method. At least you should send parameters with the null
value as the input (for nullable objects).
UPDATED: At the time you rewrote your question. So now the answer on the new version of your question.
You should use
$.ajax({
type: "POST",
url: "/myurl/jquery.aspx/GenerateUserSchedules",
data: JSON.stringify({data: [
{UserId:8},{UserId:9},{UserId:5},{UserId:13},{UserId:6},{UserId:11}]}),
contentType: "application/json",
dataType: "json",
success: function () { alert('Made It!'); },
error: function (result) { alert(Failed: ' + result.responseText);
});
The reason is easy. Because you have the method GenerateUserSchedules(User[] data)
with the data
input parameter you should use JSON.stringify({data: yourData})
as the input. The array of User
objects should be array with the items {UserId:8}
(or {'UserId':8}
or {"UserId":8}
), but not {UserId:"8"}
.
There are a couple of approaches to do this. If your application uses MS Ajax libraries by any chance then all you need to do on client side is
var jsonText = [{"UserId":"8"},{"UserId":"9"},{"UserId":"5"}];
var jsonTextSerialized = Sys.Serialization.JavaScriptSerializer.serialize(jsonText);
You can then use this jsonTextSerialized with other parameters that you have to send it to your server side code. On server side you can have
public class User{
public Int32 UserId{
get;set;
}
}
[System.Web.Script.Services.ScriptMethod]
[System.Web.Services.WebMethod]
public static void GenerateUserSchedules(string startDate, string endDate, string ddlViewSelectedItem, string ddlViewSelectedValue, string ddlOrgSelectedValue, User[] customObejct)
This should automatically do it for you.
If you are not using MS Ajax, then get JSON2.js from here
http://www.json.org/js.html
You can use this library to serialize your object on client side. On server side things should remain the same.
For more detailed guide and information also check this out
http://forums.asp.net/t/1388935.aspx
Hope this helps!
Nikhil
your custom object should now have the object
could it be as simple as:
data: "{'data':'" + jsonTextSerialized + "'}",
change to
data: '{"data":"' + jsonTextSerialized + '"}',
AND/OR change client side "UserId"
to "UserID"
Make sure the json property names and types matchup with the web method parameters. Your jsonText variable is an array and so the Web method needs a property of an array type to accept it (like in the example Nikhil posted).
So if you were using the web method signature in Nikhil's example and the custom user object, you would need to make the data property for the jquery ajax call to be:
"{'startDate':'" + startDate + "', 'endDate':'" + endDate + "', 'ddlViewSelectedItem':'" + ddlViewSelectedItem + "', 'ddlViewSelectedValue':'" + ddlViewSelectedValue + "', 'ddlOrgSelectedValue':'" + ddlOrgSelectedValue + "','customObejct':" + jsonText + "}"
精彩评论