Chris Stephens Chris Stephens - 2 years ago 309
Javascript Question

ASP.NET MVC: How to convert View Model into Json object

I am 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 JS widget object has a JSON data object that would be populated by the model data. Then methods to update this data 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.


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

return View(myview, returnData);


<%@ 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 () { = <% converttoJSON(model) %>
$(document).bind('DATA_CHANGED', thisWidgetName.updateTable());


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 seem some real simple ways to do it in the controller but not in the view. I figure this is a basic question bu I've been going for a few hours trying to make this slick.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download