How to pass Json serialized object to javascript (ASP.NET C#) - c#

i have a method that returns a list of serialized objects in my page code behind
private string Get()
{
JavaScriptSerializer jsonSerialiser = new JavaScriptSerializer();
string jsonString = SerializeToJason(UnavailabilityBusiness.Get(new DateTime()));
return jsonString ;
}
i would like to pass this serialized objects to javascript
function getJson()
{
??????
}
How do I do it?

You could write them out as a script, typically leveraging ClientScript.
You would want to take care to register the script so that it renders before the consuming script.

Looks like this guy wrote a utility class to do what you're trying to do (Code Project Link).
I have't really looked at it but you can get his source and have a look.
Good luck,
Patrick.

Related

How to generate angularjs model from c# class

The angular app I am working on has several large input forms which span several pages. The data is added to an angular model which is a javascript object literal and sent to a webApi controller. The webApi parameter for my POST methods is a C# class (duh) with a lot of properties! Is there a utility which will generate the javascript from my C# class, so that my binding just works! I've googled this and failed even though it seems such a mundane task. As always thanks in advance.
You should use JSON serialize on your JS side and deserialize on your c# side.
JS:
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonParam = oSerializer.Serialize(param);
While on your c# side you should use something like, lets say your class is Person:
C#:
Person person = new JavaScriptSerializer().Deserialize<Person>(param);
see msdn documentation on serialize\deserialize json object

WebMethod returning class object as JSON automatically

Can anyone explain me how ASP.NET handles the convertion from a class object to the JSON object in WebMethods?
For example, you have following WebMethod which returns a Person object:
[WebMethod]
public static Person GetPerson()
{
Person p = new Person()
{
Id = 1,
Name = "Test"
};
return p;
}
In my jQuery where i call the WebMethod I get a response which contains out of a json object.
How did ASP.NET do this automatcally? Does it uses the JavaScriptSerializer class?
Also you see a lot of examples of using JSON converters to convert your class object to a json object. Why is this? Is it because of the JavaScriptSerializer class it uses and its bad performance or... ?
How did ASP.NET do this automatically?
Basically there's some code sitting between the web and the WebMethod that takes the request, figures out what it's requesting, finds your WebMethod and obtains the result, then serializes it back to the client based on the acceptable formats in the request header.
Does it uses the JavaScriptSerializer class?
Probably. I couldn't find anything out there that stated it. But it doesn't use any third party library. Since that's one is built in, that's a good assumption.
Also you see a lot of examples of using JSON converters to convert
your class object to a json object. Why is this? Is it because of the
JavaScriptSerializer class it uses and its bad performance or... ?
WebMethod technique can be very finicky and sometimes will refuse to return JSON, despite the accept headers. One way around that is to do something like this:
[WebMethod]
public static void GetPerson()
{
Person p = new Person()
{
Id = 1,
Name = "Test"
};
HttpContext.Current.Response.ResponseType = "application/json";
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(p));
HttpContext.Current.Response.End();
}
You lose content negotiation (unless you manually implement it by inspecting the request headers), but you get more control over how it's serialized.

Convert C# object to JSON or Javascript object

I am a C# developer and a newbi in Javascript.
I have one C# object and finally, in index.cshtml, I can get a string converted from the object via calling Json.Encode(obj)
The string is:
[
{
"Name":"CASE_A",
"Values":[99.8,99.9,99.9,99.8,99.8,96.3,22.3]
},
{
"Name":"CASE_B",
"Values":[99.8,99.8,99.8,96.3,22.3]
},
]
However, when I call JSON.parse(#TheString),I got:
Uncaught SyntaxError: Unexpected token &
The location of this error shows me this:
data = JSON.parse([{"Name":"CASE_A","Values":[99.8,99.9,99.9,99.8 ....
How can I fix this problem?
Thank you for the answers!
But still I got an error:
Uncaught SyntaxError: Unexpected token o
For simple testing, I used this:
#{
string tmp = "[{\"Name\":\"CASE_A\",\"Values\":[99.8,99.9,98.6]},{\"Name\":\"CASE_B\",\"Values\":[96.7,11.1]}]";
}
var data1 = JSON.parse(#Html.Raw(#tmp));
And source shows this line:
var data1 = JSON.parse([{"Name":"CASE_A","Values":[99.8,99.9,98.6]},{"Name":"CASE_B","Values":[96.7,11.1]}]);
I cannot see any "o" here.
Also, for making javascript object, Travis suggested to remove the key name before serialization. But in C#, all object must have its member name. All I can think of is string manipulation. Is there any better way to do so?
Razor will automatically escape HTML entities for you in an attempt to be helpful. You can disable this with Html.Raw:
JSON.parse(#Html.Raw(TheString))
For your second error, JSON.parse expects a string, but you are passing in an array. Your outputted js code has to look like this to work:
var data1 = JSON.parse("[{\"Name\":\"CASE_A\",\"Values\":[99.8,99.9,98.6]},{\"Name\":\"CASE_B\",\"Values\":[96.7,11.1]}]");
I also want to note that since you are injecting this object into your javascript code on the server side, there is no need to call JSON.parse at all. As long as you send properly formatted javascript to the client where it will be evaluated and run, then it doesn't matter how it's created on the server. Try this instead:
var data1 = #Html.Raw(#tmp);
You may try this using HtmlHelper.Raw method:-
data = JSON.parse(#Html.Raw(TheString));
Also check out DataContractJsonSerializer Class
Serializes objects to the JavaScript Object Notation (JSON) and
deserializes JSON data to objects. This class cannot be inherited.
Using the string will cause Razor to protect you from injection. If you are passing in json chances are that isn't an issue. Common practice is to use the Html.Raw helper
data = JSON.parse( #(Html.Raw(TheString)) );
OP's solution worked for me as well.
data = eval(JSON.parse(#Html.Raw(TheString)))
If you have a C# Object and want to use it in JavaScript as is, you can do:
var jsObject = #Html.Raw(JsonConvert.SerializeObject(TheString));
You'll need to add the nuget package and import the dll in _ViewImports.cshtml:
#using Newtonsoft.Json;
Hope it helps someone...

Reading JavaScriptSerializer c# back in javascript

In one of my webservice methods I serialized my object calling JavaScriptSerializer.serilize in c#. Now when that returns a string to my javascript I would like to be able to call the properties from the object. I tried, results.d.ID but that did not work. Here is what it returns. Thanks for any help.
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
Inventory item = Inventories.GetInventoryByID(inventoryID);
string jsonObject = oSerializer.Serialize(item);
For example I would like to get the ID out. how would I do that?
{"d":"{\"ID\":\"589652cf-2ccd-49c1-b457-f2793a2a2424\",\"Brand\":{\"ID\":\"b728281b-cf3c-4ee0-ba3d-a3573b886b14\",\"Name\":\"Puma1\",\"ParentBrand\":null,\"BrandChildren\":{\"IsValueCreated\":false,\"Value\":[]}},\"DateAdded\":\"\\/Date(1327695794000)\\/\",\"AddedBy\":{\"ID\":\"d6e1f2e7-f8d1-4809-aadd-4cacd5c2bc43\",\"Email\":\"mojo#yahoo.com\",\"FirstName\":\"maurice\",\"MiddleInitial\":\"l\",\"LastName\":\"bachelor\",\"Address\":\"111 main st\",\"Phone\":\"2162330333\",\"IsAdmin\":true,\"DateJoined\":\"\\/Date(-62135578800000)\\/\",\"HasPurchased\":false,\"AgreeTerms\":true,\"LastPurchaseDate\":null,\"Password\":\"maurice\",\"CompanyName\":\"sneakers101\",\"AllowEmail\":false,\"PurchaseOrders\":{\"IsValueCreated\":false,\"Value\":[]}},\"LastUpdated\":\"\\/Date(1327688594000)\\/\",\"Instock\":true,\"NumberInStock\":12,\"MainPictureUrl\":\"\",\"AlternativePictureUrl\":\"\",\"ThumbNailUrl\":\"\",\"Price\":12.99,\"Like\":0,\"Discount\":1,\"ItemReleaseDate\":\"\\/Date(568011600000)\\/\",\"ItemCondition\":\"Great\",\"Size\":12,\"ItemNumber\":3,\"IsFavorite\":false,\"Details\":\"test Details\",\"Name\":\"Test\"}"}
As Inerdial said you have strange nested JSON value. If data is in format you actually want - use JSON.parse to re-parse values like:
JSON.parse(results.d).ID.
Here's what it's all about: asp.net's ajax d
var jsonObj = theObject; // Assuming it is parsed somehow
var embeddedJsonObj = $.parseJSON( jsonObj.d );
// embeddedJsonObj.ID is the ID you need.
Demo
It looks like your underlying problem is the manually JSON serialization.
Since ASP.NET will automatically JSON serialize the result of your method, your manually serialized jsonObject string is then getting serialized a second time. That's why Alexei's answer works. jQuery deserialized it once, leaving you with a .d property containing a JSON string, and then JSON.parse() deserialized that inner JSON string.
However, that is doubly inefficient because your data is being serialized twice and deserialized twice. Instead, just do this:
[WebMethod]
public Inventory GetInventoryById(inventoryID) {
return item = Inventories.GetInventoryByID(inventoryID);
}
Then, ASP.NET will return JSON that looks like this:
{"d": {"ID": "589652cf-2ccd-49c1-b457-f2793a2a2424", /* the rest of your data here */ }}
Which jQuery (assuming you're using jQuery) will automatically JSON.parse() since ASP.NET responds with an application/json Content-Type, and then you'll be able to index into like results.d.ID.

Json Object Deserialization in c#

im tyring to deserialize my object coming from client side having following format:
{'goalplans':
[{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0}
]}
thing is that im not able to deserialze it on my server side .
Please tell me how can i deserialize the Json object to a list object like
List . i tried many ways but not working.
serialize/deserialize objects to/from JSON exist Since .NET 3.5, try this
using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
See here for more details
Hope this helps
One possible third party component is JSON.NET. Personally I have made very good experience with that library ( it is available using nuget for example )
I solved the problem by myself. Simply adding [Serializable] to my class
and changed method to take argument of class type ...
e.g.
//My class
[Serializable]
public class GoalPlanList{}
//method
public static int GoalplanAddUPD(List<GoalPlanList> goalplans)
{
foreach (GoalPlanList goals in goalplans)
{}
}

Categories