My Technical Notes

Sunday, 3 October 2010

Rendering Json in MVC

To render Json into an MVC view, you will need to use `System.Web.Script.Serialization.JavaScriptSerializer` which MVC uses internally when you call JsonResult.

Ideally what we would like to do is render a JSON object onto the page and then be able to refer to it through our script. For this we must attach it to the `window` object:

public static void RenderJson(this HtmlHelper html, string name, object o)
    var startTag = "<script type='text/javascript'>";
    var endTag = "</script>";

    var jsonObj = new JavaScriptSerializer().Serialize(o);

    var decl = "window." + name + "=" + jsonObj + ";";

    var script = startTag
               + decl
               + endTag;

Then in our views we can then render a specific object that was passed to it from the controller:

<% Html.RenderJson("persons", ViewData["PersonList"]); %>
Then in our Javascript, we can then refer to the object using the `window[object-name]` property:

<script type="text/javascript">

No comments: