@{
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