"Invalid JSON primitive" in Ajax processing - c#
I am getting an error in an ajax call from jQuery.
Here is my jQuery function:
function DeleteItem(RecordId, UId, XmlName, ItemType, UserProfileId) {
var obj = {
RecordId: RecordId,
UserId: UId,
UserProfileId: UserProfileId,
ItemType: ItemType,
FileName: XmlName
};
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
if (msg.d != null) {
RefreshData(ItemType, msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error occured during deleting");
}
});
}
and this is my WebMethod:
[WebMethod]
public static string DeleteRecord(Int64 RecordId, Int64 UserId, Int64 UserProfileId, string ItemType, string FileName) {
try {
string FilePath = HttpContext.Current.Server.MapPath(FileName);
XDocument xmldoc = XDocument.Load(FilePath);
XElement Xelm = xmldoc.Element("UserProfile");
XElement parentElement = Xelm.XPathSelectElement(ItemType + "/Fields");
(from BO in parentElement.Descendants("Record")
where BO.Element("Id").Attribute("value").Value == RecordId.ToString()
select BO).Remove();
XDocument xdoc = XDocument.Parse(Xelm.ToString(), LoadOptions.PreserveWhitespace);
xdoc.Save(FilePath);
UserInfoHandler obj = new UserInfoHandler();
return obj.GetHTML(UserId, UserProfileId, FileName, ItemType, RecordId, Xelm).ToString();
} catch (Exception ex) {
HandleException.LogError(ex, "EditUserProfile.aspx", "DeleteRecord");
}
return "success";
}
Can anybody please tell me what's wrong in my code?
I am getting this error:
{
"Message":"Invalid JSON primitive: RecordId.",
"StackTrace":"
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)
at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType":"System.ArgumentException"
}
Just a guess what does the variable json contain after
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?
If it is a valid json object like {"foo":"foovalue", "bar":"barvalue"} then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue thus you get the error "Invalid JSON primitive: foo"
Try instead setting the data as string
$.ajax({
...
data: '{"foo":"foovalue", "bar":"barvalue"}', //note the additional quotation marks
...
})
This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.
Using
data : JSON.stringify(obj)
in the above situation would have worked I believe.
Note: You should add json2.js library all browsers don't support that JSON object (IE7-)
Difference between json.js and json2.js
it's working
something like this
data: JSON.stringify({'id':x}),
As noted by jitter, the $.ajax function serializes any object/array used as the data parameter into a url-encoded format. Oddly enough, the dataType parameter only applies to the response from the server - and not to any data in the request.
After encountering the same problem I downloaded and used the jquery-json plugin to correctly encode the request data to the ScriptService. Then, used the $.toJSON function to encode the desired arguments to send to the server:
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: $.toJSON(obj),
contentType: "application/json; charset=utf-8",
dataType: "json"
....
});
Jquery Ajax will default send the data as query string parameters form like:
RecordId=456&UserId=123
unless the processData option is set to false, in which case it will sent as object to the server.
contentType option is for the server that in which format client has sent the data.
dataType option is for the server which tells that what type of data
client is expecting back from the server.
Don't specify contentType so that server will parse them as query
String parameters not as json.
OR
Use contentType as 'application/json; charset=utf-8' and use JSON.stringify(object) so that server would be able to deserialize json from string.
I guess #jitter was right in his guess, but his solution didn't work for me.
Here is what it did work:
$.ajax({
...
data: "{ intFoo: " + intFoo + " }",
...
});
I haven't tried but i think if the parametter is a string it should be like this:
$.ajax({
...
data: "{ intFoo: " + intFoo + ", strBar: '" + strBar + "' }",
...
});
I was facing the same issue, what i came with good solution is as below:
Try this...
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: '{RecordId: ' + RecordId + ', UserId: ' + UId + ', UserProfileId:' + UserProfileId + ', ItemType: \'' + ItemType + '\', FileName: '\' + XmlName + '\'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
if (msg.d != null) {
RefreshData(ItemType, msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error occured during deleting");
}
});
Please note here for string type parameter i have used (\') escape sequence character for denoting it as string value.
Here dataTpe is "json" so, data/reqParam must be in the form of string while calling API,
many as much as object as you want but at last inside $.ajax's data stringify the object.
let person= { name: 'john',
age: 22
};
var personStr = JSON.stringify(person);
$.ajax({
url: "#Url.Action("METHOD", "CONTROLLER")",
type: "POST",
data: JSON.stringify( { param1: personStr } ),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Success");
},
error: function (error) {
console.log("error found",error);
}
});
OR,
$.ajax({
url: "#Url.Action("METHOD", "CONTROLLER")",
type: "POST",
data: personStr,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Success");
},
error: function (error) {
console.log("error found",error);
}
});
If manually formatting JSON, there is a very handy validator here: jsonlint.com
Use double quotes instead of single quotes:
Invalid:
{
'project': 'a2ab6ef4-1a8c-40cd-b561-2112b6baffd6',
'franchise': '110bcca5-cc74-416a-9e2a-f90a8c5f63a0'
}
Valid:
{
"project": "a2ab6ef4-1a8c-40cd-b561-2112b6baffd6",
"franchise": "18e899f6-dd71-41b7-8c45-5dc0919679ef"
}
On the Server, to Serialize/Deserialize json to custom objects:
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
I had the same issue. I was calling parent page "Save" from Popup window Close. Found that I was using ClientIDMode="Static" on both parent and popup page with same control id. Removing ClientIDMode="Static" from one of the pages solved the issue.
these answers just had me bouncing back and forth between invalid parameter and missing parameter.
this worked for me , just wrap string variables in quotes...
data: { RecordId: RecordId,
UserId: UId,
UserProfileId: UserProfileId,
ItemType: '"' + ItemType + '"',
FileName: '"' + XmlName + '"'
}
Related
Get ASP Page Method return from jQuery
I have an aspx page. I want to call the ASP.NET method via jquery. I have implemented the code but the problem is that I am getting the HTML of whole page rather than getting the returned string from ASP method. I need some assistance. Here is my code: [WebMethod] public string PopulateData(string coursename) { return "called"; } and here is the jquery method: var subject = 'database'; $.ajax({ type: "POST", url: "CourseDetail.aspx/PopulateData", data: "{coursename:'" + subject + "'}", success: function (msg) { // Do something interesting here. alert('result : ' + msg); }
Add in the contentType and dataType. var subject = 'database'; $.ajax({ type: "POST", dataType: "text", contentType: "application/json; charset=utf-8", url: "CourseDetail.aspx/PopulateData", data: "{coursename:'" + subject + "'}", success: function (msg) { // Do something interesting here. alert('result : ' + msg); } contentType is the header sent to the server, specifying a particular format. Example: I'm sending json or XML dataType is telling jQuery what kind of response to expect. Expecting JSON, or XML, or HTML, etc....
How to call webmethod in Asp.net C#
I want to call a web method in asp.net c# application using the following code Jquery: jQuery.ajax({ url: 'AddToCart.aspx/AddTo_Cart', type: "POST", data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}", contentType: "application/json; charset=utf-8", dataType: "json", beforeSend: function () { alert("Start!!! "); }, success: function (data) { alert("a"); }, failure: function (msg) { alert("Sorry!!! "); } }); C# Code: [System.Web.Services.WebMethod] public static string AddTo_Cart(int quantity, int itemId) { SpiritsShared.ShoppingCart.AddItem(itemId, quantity); return "Add"; } But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine. Script example: $.ajax({ type: "POST", url: '/Default.aspx/TestMethod', data: '{message: "HAI" }', contentType: "application/json; charset=utf-8", success: function (data) { console.log(data); }, failure: function (response) { alert(response.d); } }); WebMethod example: [WebMethod] public static string TestMethod(string message) { return "The message" + message; }
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong: data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}", It should be: data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}", As well as the WebMethod to: public static string AddTo_Cart(string quantity, string itemId) And this resolved my problem. Hope it may be of help to someone else as well.
Necro'ing this Question ;) You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function. First Step: Extract data construction /*** * This helper is used to call WebMethods from the page WebMethods.aspx * * #method - String value; the name of the Web Method to execute * #data - JSON Object; the JSON structure data to pass, it will be Stringified * before sending * #beforeSend - Function(xhr, sett) * #success - Function(data, status, xhr) * #error - Function(xhr, status, err) */ function AddToCartAjax(method, data, beforeSend, success, error) { $.ajax({ url: 'AddToCart.aspx/', + method, data: JSON.stringify(data), type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", beforeSend: beforeSend, success: success, error: error }) } Second Step: Generalize WebMethod [WebMethod] public static string AddTo_Cart ( object items ) { var js = new JavaScriptSerializer(); var json = js.ConvertToType<Dictionary<string , int>>( items ); SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]); return "Add"; } Third Step: Call it where you need it This can be called just about anywhere, JS-file, HTML-file, or Server-side construction. var items = { "quantity": total_qty, "itemId": itemId }; AddToCartAjax("AddTo_Cart", items, function (xhr, sett) { // #beforeSend alert("Start!!!"); }, function (data, status, xhr) { // #success alert("a"); }, function(xhr, status, err){ // #error alert("Sorry!!!"); });
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary : [System.Web.Services.WebMethod] public static string AddTo_Cart(string quantity, string itemId) { //parse parameters here SpiritsShared.ShoppingCart.AddItem(itemId, quantity); return "Add"; } Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help. Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable. jQuery jQuery.ajax({ url: 'AddToCart.aspx', type: "POST", data: { method: 'AddTo_Cart', quantity: total_qty, itemId: itemId }, dataType: "json", beforeSend: function () { alert("Start!!! "); }, success: function (data) { alert("a"); }, failure: function (msg) { alert("Sorry!!! "); } }); C# Page Load: if (!Page.IsPostBack) { if (Request.Form["method"] == "AddTo_Cart") { int q, id; int.TryParse(Request.Form["quantity"], out q); int.TryParse(Request.Form["itemId"], out id); AddTo_Cart(q,id); } }
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events.. Please refer below page for more details http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer. use jquery.json-2.2.min.js and jquery-1.8.3.min.js Javascript : function CallAddToCart(eitemId, equantity) { var itemId = Number(eitemId); var quantity = equantity; var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ; $.ajax({ url: "AddToCart.aspx/AddTo_Cart", type: "POST", dataType: "json", data: dataValue, contentType: "application/json; charset=utf-8", success: function (msg) { alert("Success"); }, error: function () { alert(arguments[2]); } }); } and your C# web method should be [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string AddTo_Cart(int itemId, string quantity) { SpiritsShared.ShoppingCart.AddItem(itemId, quantity); return "Item Added Successfully"; } From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.
asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'
I want to insert data from JavaScript to database using ajax and webservice, I have some controls which by jQuery I get their values and make an array of their values. When I send the array it causes this error: Cannot convert object of type 'System.String' to type'System.Collections.Generic.List1[System.String]' var variables = Array(); var i=0; $('#Div_AdSubmition').find('.selectBox').each(function () { variables[i] = $(this).find('.selected').find(".text").html(); i++; }); $.ajax({ type: 'post', data: "{ 'a':'" +variables + "'}", dataType: 'json', url: 'HomeWebService.asmx/insertAd', contentType: 'application/json; charset=utf-8', success: function (data) { alert("data : " + data.d); } }); This is the C# Code [WebMethod] public object insertAd(List<string> a) { return a; }
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables}) The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here Also, you had an extra } in the success function. So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so: var someArr = ['el1', 'el2']; JSON.stringify({ 'param1': 1, 'param2': 'two' 'param3': someArr // etc }); JavaScript: var variables = Array(); var i = 0; $('#Div_AdSubmition').find('.selectBox').each(function () { variables[i] = $(this).find('.selected').find(".text").html(); i++; }); $.ajax({ type: 'post', data: JSON.stringify({'a': variables}), dataType: 'json', url: 'HomeWebService.asmx/insertAd', contentType: 'application/json; charset=utf-8', success: function (data) { alert("data : " + data.d); }); }); C# [WebMethod] public object insertAd(List<string> a) { return a; }
data: Data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting. So, try to add a new parameter to your ajax call: $.ajax({ type: 'post', data: { 'a': variables }, // Notice some changes here dataType: 'json', traditional: true, // Your new parameter url: 'HomeWebService.asmx/insertAd', contentType: 'application/json; charset=utf-8', success: function (data) { alert("data : " + data.d); } }); Try this way. Maybe you'll need to change the Web service method to expect an array instead of a List, but I'm not sure.
Try this data: JSON.stringify({ 'a': variables }),
What is contentType and dataType and data in jQuery ajax Post?
I have just started to Learn the Json and binding data to Gridview using Json but I am not able to understand what is the contentType and dataType and data ? I used the Following code............ <script type="text/javascript"> $(document).ready(function () { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Gridview.aspx/BindDatatable", data: "{}", dataType: "json", success: function (data) { for (var i = 0; i < data.d.length; i++) { $("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>"); } }, error: function (result) { alert("Error"); } }); }); </script>
The contentType referres to the mime content type that specifies the type of content set to the server. This could indentify FORM-Encoded, XML, JSON and a plethora of other content types. It helps the server to determine how to handle the content. dataType helps JQuery with regards to how to handle the data. if specifying json then the returned data will be evaluated as json and data passed to the success handler will be an object instead of a string The data property is used for data passed to The server. If you pass in an Object literal. JQuery will pass it either as part of the request body (if type is post) or as part of the query string (if type is get)
if we specify the data type as Json then the returned data will be evaluated as Json and data passed to the success handler will be an object instead of string,Lets see the example $.ajax({ type: "POST", url: "ProductWebService.asmx/GetProductDetails", data: "{'productId':'" + productId + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { var Product = response.d; $("#spnProductId").html(Product.Id);strong text $("#spnProductName").html(Product.Name); $("#spnPrice").html(Product.Price); $("#outputTable").show(); }, failure: function (msg) { alert(msg); } });
How to pass a JSON array in javascript to my codebehind file
I am getting a JSON object in my javascript function in aspx page. I need to fetch this data from my code behind file. How can I do it? My javascript function is : function codeAddress() { var address = document.getElementById("address").value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert("Geocode was not successful for the following reason: " + status); } var requestParameter = '{' + 'output:"' + results + '"}'; $.ajax({ type: "POST", url: "Default.aspx/GetData", data: requestParameter, //contentType: "plain/text", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert(msg.d); }, error: function() { alert("error"); } }); }); } Default.aspx.cs [WebMethod] public static string GetData( Object output) { return output.ToString(); } I am getting the output as an array of objects instead of the actual result - [object Object],[object Object],[object Object] .Please provide me a solution to get the actual result. The JSON I am working on is given below http://maps.googleapis.com/maps/api/geocode/json?address=M%20G%20Road&sensor=false
Create a WebMethod on your aspx Page that get the array on the page as: [WebMethod] public static GetData( type[] arr) // type could be "string myarr" or int type arrary - check this {} and make json request. $.ajax({ type: 'POST', url: 'Default.aspx/GetData', data: "{'backerEntries':" + backerEntries.toString() + "}", contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(response) {} }); or you can use .post(). Check the url: in ajax request GetData WebMethod must be declared on the Default.aspx on that page where you are making ajax request. Check this question to know that how to format array for sending to the web method. Why doesn't jquery turn my array into a json string before sending to asp.net web method? Check these links for reference: Handling JSON Arrays returned from ASP.NET Web Services with jQuery - It is Best to take idea How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?