Friday, March 30, 2012

ASP.NET MVC 3 - Converting / Serializing .Net objects into JSON format in View


In ASP.NET MVC often we might need to use / manipulate Model objects or its property inside the javascript. In order to achieve that, we usually try to serialize the .Net object and store it in a javascript variable which will then be accessed further in javascript.

Using Razor view engine, we can achieve this easily. In the following, I'll explain two approaches with a simple View(.cshtml) snippet to understand the concept. 

Approach 1: (Using Json.Encode(...))

Snippet 1: (Index.cshtml)

@model Web.POC.Models.FeedModel
@{
    ViewBag.Title = "Feed viewer";
}

<script type="text/javascript">
    var entries = @Html.Raw(Json.Encode(Model.FeedEntries));    
</script>


Approach 2: (Using JavaScriptSerializer)

Snippet 2: (Index.cshtml)

@model Web.POC.Models.FeedModel
@{
    ViewBag.Title = "Feed viewer";
}

@{
   System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
}
<script type="text/javascript">
    var entries = @Html.Raw(serializer.Serialize(Model.FeedEntries));    
</script>


Assumptions:

As specified, the above snippets are just to understand the concept. In that, consider that we're having a model "FeedModel" which holds a property called "FeedEntries" of some custom type which we're trying to convert into JSON object.

Also note that we need to use the HTML.Raw() to indicate that the output should not be HTML encoded.


3 comments:

  1. hi.Your approach is very good.but when i am using your second approach for serializer in mvc4 it gives me error that The name 'Serialize' does not exist in the current context how to solve it?

    ReplyDelete
    Replies
    1. Hi Vaibhav, currently I'm unable to verify the issue specified by you. But still please verify that whether your project has reference to System.Web.Extensions.dll. For more details please refer the msdn reference http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx.
      If, still problem exists, please let me know - by the time will be ready to verify the issue.

      Delete

Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.