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.
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?
ReplyDeleteHi 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.
DeleteIf, still problem exists, please let me know - by the time will be ready to verify the issue.
Nice example - cheers.
ReplyDelete