07 December 2011

MVC/JavaScript - Serialize an object on the server to use in JavaScript using JSON

While coding a project in MVC, I wanted to serialize an object in C#, put it in the ViewBag and on the client have JQuery parse it back into an object for JavaScript to use. It can be done like this:

Server side

In the controller action, simply serialize the object this way:
ViewBag.DataFilter = new JavaScriptSerializer().Serialize(filter);
Where filter is the object.

Client side

On the client, you can parse it back like this:
//Parse
parser = document.createElement('div');
parser.innerHTML = '@(ViewBag.DataFilter)';
var DataFilter = $.parseJSON(parser.innerHTML);
//Test
alert(DataFilter.Fields[0].FieldName);
And that's all there's to it.

No comments:

Post a Comment