Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Tuesday, January 24, 2012

Converting .Net Object In To JSON Object ASP.Net MVC

If you want to convert your .Net object in to a JSON object in the view the first thing you can use is to use System.Web.Script.Serialization.JavaScriptSerializer object and convert it in to JSON.
@{
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