@{ System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //.... <script> var s = @serializer.Serialize(Model); </script> }
This is MVC3 Razor syntax. The problem here is in the @ sign it will again HTML encode the JSON object which lead you to flowing error.
var s = { "Name":"a","Id":1}; Create:228Uncaught SyntaxError: Unexpected token &
To avoid this we can use HTML.Raw() helper method like below.
var s = @HTML.Raw(serializer.Serialize(Model));
The easiest and the most reusable way of doing it is to write a helper method link this,
public static MvcHtmlString ToJson(this HtmlHelper html, object obj) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return MvcHtmlString.Create(serializer.Serialize(obj)); }
And then in the view we can use this helper method
This is a good post can you please update some more about j son. I have some requirement like convert a Web API to j son and XML.
ReplyDeletePlease write something about it and it is more helpful if you use sime images or demo download which was error free.
Regards.
Atul D
I think you can request whatever the data type from the client side and get the relevant datatype back. This is one of the most advantages of web api. You just need to set the content type of the request .
DeleteAccept or Content-Type request headers. http://stackoverflow.com/questions/9847564/how-do-i-get-mvc-4-webapi-to-return-json-instead-of-xml-using-chrome