How to convert View Model into JSON object in ASP.NET MVC?

Chris Stephens picture Chris Stephens · Jul 29, 2010 · Viewed 215.8k times · Source

I am a Java developer, new to .NET. I am working on a .NET MVC2 project where I want to have a partial view to wrap a widget. Each JavaScript widget object has a JSON data object that would be populated by the model data. Then methods to update this data are bound to events when data is changed in the widget or if that data is changed in another widget.

The code is something like this:

MyController:

virtual public ActionResult DisplaySomeWidget(int id) {
  SomeModelView returnData = someDataMapper.getbyid(1);

  return View(myview, returnData);
}

myview.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModelView>" %>

<script type="text/javascript">
  //creates base widget object;
  var thisWidgetName = new Widget();

  thisWidgetName.updateTable = function() {
    //  UpdatesData
  };
  $(document).ready(function () {
    thisWidgetName.data = <% converttoJSON(model) %>
    $(document).bind('DATA_CHANGED', thisWidgetName.updateTable());
  });
</script>

<div><%:model.name%></div>

What I don’t know is how to send the data over as SomeModelView and then be able to use that to populate the widget as well as convert that to JSON. I had seen some real simple ways to do it in the controller but not in the view. I figure this is a basic question but I’ve been going for a few hours trying to make this slick.

Answer

Dave picture Dave · Sep 20, 2011

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.