Ajax cannot read Serialized Json dictionary correctly - c#

This is what I have in my c# code
using Newtonsoft.Json;
.....
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("id", id.ToString());
d.Add("type", "error");
d.Add("msg", pex.Message);
.....
return JsonConvert.SerializeObject(d);
My AJAX
......
$.ajax({
type: "POST",
url: "Service1.svc/MyCall",
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
beforeSend: function () {
$("#lblResult").html("loading");
},
success: function (data) {
$("#lblResult").html(data['id']);
},
......
This is the response in Firebug
"{\"id\":\"1\",\"type\":\"error\",\"msg\":\"An exception occurred during a Ping request.\"}"
This is the JSON in Firebug
0 "{"
1 """
2 "i"
3 "d"
4 """
5 ":"
6 """
7 "1"
8 """
9 ","
10 """
11 "t"
ETC
Problem: I cannot get data['id'] or any data['SOMETHING'].
How can I get it based on the response received?
Any other way to do all?

This looks like the JSON is not being converted back to a JavaScript object correctly. Try this
success: function (data) {
if (data.hasOwnProperty("d"))
{
var response = JSON.parse(data.d);
$("#lblResult").html(response["id"]);
}
else
{
var response = JSON.parse(data);
$("#lblResult").html(response["id"]);
}
}
The .d is required as .Net adds this for security reasons, a better explanation than I can give can be found here Why do ASP.NET JSON web services return the result in 'd'?.
Then since the returned value is a JSON string, this needs to be parsed to become the Javascript Object

Related

JavaScript - extracting data from a JSON object created with Json.Net

I have a server-side method used to return the data to the user. The data is stored in a SQL Server database and is mapped using EF 6. Once extracted from the database using an id value, the object is subsequently serialized using the Json.NET framework. The object is used "as is", without filtering out the references to other tables. Because of that, I've had to use the "PreserveReferencesHandling" option.
On the client-side, AJAX is used to call the method. I'm having trouble extracting the data from the object (client-side) which does get serialized and is delivered to the browser as expected.
Server-side method:
[WebMethod]
public static string ContactData(long id)
{
IService<Contact> contactService = new ContactService();
Contact contactEdit = contactService.GetById(id);
string str = JsonConvert.SerializeObject(contactEdit, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
return str;
}
Client-side function (the important part):
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact) {
$("#tbFirstName").val(contact.d[0].Contact.first_name); // I've tried various combinations to no avail
},
});
This is how the JSON object (testing purposes data) looks like in Visual Studio's JSON Visualizer:
And this is what the browser (FF 32, it that matters) receives:
Firebug
I will post more info if needed.
First parse the json before you process it. and loop through it using jquery each function.
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact)
{
var contact=jQuery.parseJSON(contact);
$.each(contact, function(i, item) {
alert(i + " ==> "+ item.first_name);
});
}
});

Read and Parse JSON data from POST request in C#

I'm doing a POST request via JQuery's Ajax, with the type of data defined as json, containing the values to be posted to server, something like Username: "Ali".
What I need to do in a Handler, is to read the values, deserialize them to an object named User.
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
User user = JsonConvert.DeserializeObject<User>(data);
While debugging, the value of data is the following:
Username=Ali&Age=2....
Now I'm sure this isn't JSON, so the next line would certainly produce an error:
"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
What is the proper way to read JSON data from POST request?
Client Side
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: {
Username: 'Ali',
Age: 2,
Email: 'test'
},
success: function (data) {
},
error: function (error) {
}
});
Convert your object to json string:
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: JSON.stringify({
Username: 'Ali',
Age: 2,
Email: 'test'
}),
success: function (data) {
},
error: function (error) {
}
});
I am not sure why your datastring is encoded like an url (as it seems).
But this might solve the problem (altough i am not sure)
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
String fixedData = HttpServerUtility.UrlDecode(data);
User user = JsonConvert.DeserializeObject<User>(fixedData);
Use This In c# file... Will give you result you require...
string username=Request.Form["Username"].ToString();
Similarly For others...
I hope this will help you
Another Answer Or you can send data like this
$.ajax({
url: '../Ajax/Ajax_MasterManagement_Girdle.aspx',
data: "Age=5&id=2"
type: 'POST',
success: function (data) {
}
});
ANd get the answer like this in c#
string Age=Request.Form["Age"].ToString();

Send complex data to C# with jQuery

I have a JavaScript object like so that I want to send to C# (question right at the bottom)
var data = {
mykey1: "somevalue",
mykey2: "somevalue2",
addProducts: [
{
id: 1,
quantity: 3,
variation: 54
},
{
id: 2,
quantity: 5,
variation: 23
}
]
}
It is to add either a single product or multiple products to a users basket. I want to send an array of objects back..
I can access this in Javascript by using
data.addProducts[1].id
using the below...
$.ajax({
url: "/ajax/myurl",
data: data,
dataType: "json",
type: "GET",
success: function( response ){
// Data returned as JSON
}
});
it is sending the data like this (URLdecoded for your reading pleasure)
?mykey1=somevalue&mykey2=somevalue2&addProducts[0][id]=1&addProducts[0][quantity]=3&addProducts[0][variation]=54&addProducts[0][id]=2&addProducts[0][quantity]=5&addProducts[0][variation]=23
My question is... without using JSON.stringify on the data, which will just send it as a full object in the url /ajax/myurl/{mykey1:1 ...}
How can I read this information back in from C#? jQuery is just encoding it as the standard way, should I be doing anything else to this, and is there a built in way to grab this data in C#?
var strValue = $(getStringValue);
var intValue = $(getIntValue)
$.ajax({
type: \"post\",
url: \"default.aspx/getData\",
data: \"{\'postedAjaxStringValue\"\': \'\" + encodeURIComponent(strValue) + \"\', postedAjaxIntValue: \" + encodeURIComponent(intValue ) + \"}\",
contentType: \"application/json; charset=utf-8\",
dataType: \"json\",
success: OnSuccess,
failure: function (response) {
error: function (response) {
});
//ON C# KodeBehind..
[System.Web.Services.WebMethod]
public static string getData(string postedAjaxStringValue, int postedAjaxIntValue){}

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?

"Invalid JSON primitive" in Ajax processing

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 + '"'
}

Categories

Resources