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

.NetJavascriptasp.net MvcJson

.Net Problem Overview


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.

.Net Solutions


Solution 1 - .Net

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

Solution 2 - .Net

Well done, you've only just started using MVC and you've found its first major flaw.

You don't really want to be converting it to JSON in the view, and you don't really want to convert it in the controller, as neither of these locations make sense. Unfortunately, you're stuck with this situation.

The best thing I've found to do is send the JSON to the view in a ViewModel, like this:

var data = somedata;
var viewModel = new ViewModel();
var serializer = new JavaScriptSerializer();
viewModel.JsonData = serializer.Serialize(data);

return View("viewname", viewModel);

then use

<%= Model.JsonData %>

in your view. Be aware that the standard .NET JavaScriptSerializer is pretty crap.

doing it in the controller at least makes it testable (although not exactly like the above - you probably want to take an ISerializer as a dependency so you can mock it)

Update also, regarding your JavaScript, it would be good practice to wrap ALL the widget JS you have above like so:

(
    // all js here
)();

this way if you put multiple widgets on a page, you won't get conflicts (unless you need to access the methods from elsewhere in the page, but in that case you should be registering the widget with some widget framework anyway). It may not be a problem now, but it would be good practice to add the brackets now to save yourself muchos effort in the future when it becomes a requirement, it's also good OO practice to encapsulate the functionality.

Solution 3 - .Net

I found it to be pretty nice to do it like this (usage in the view):

    @Html.HiddenJsonFor(m => m.TrackingTypes)

Here is the according helper method Extension class:

public static class DataHelpers
{
	public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
	{
		return HiddenJsonFor(htmlHelper, expression, (IDictionary<string, object>) null);
	}

	public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
	{
		return HiddenJsonFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
	}

	public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
	{
		var name = ExpressionHelper.GetExpressionText(expression);
		var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

		var tagBuilder = new TagBuilder("input");
		tagBuilder.MergeAttributes(htmlAttributes);
		tagBuilder.MergeAttribute("name", name);
		tagBuilder.MergeAttribute("type", "hidden");

		var json = JsonConvert.SerializeObject(metadata.Model);

		tagBuilder.MergeAttribute("value", json);

		return MvcHtmlString.Create(tagBuilder.ToString());
	}
}

It is not super-sofisticated, but it solves the problem of where to put it (in Controller or in view?) The answer is obviously: neither ;)

Solution 4 - .Net

You can use Json from the action directly,

Your action would be something like this:

virtual public JsonResult DisplaySomeWidget(int id)
{
    SomeModelView returnData = someDataMapper.getbyid(id);
    return Json(returnData);
}

Edit

Just saw that you assume this is the Model of a View so the above isn't strictly correct, you would have to make an Ajax call to the controller method to get this, the ascx would not then have a model per se, I will leave my code in just in case it is useful to you and you can amend the call

Edit 2 just put id into the code

Solution 5 - .Net

@Html.Raw(Json.Encode(object)) can be used to convert the View Modal Object to JSON

Solution 6 - .Net

Extending the great answer from Dave. You can create a simple HtmlHelper.

public static IHtmlString RenderAsJson(this HtmlHelper helper, object model)
{
    return helper.Raw(Json.Encode(model));
}

And in your view:

@Html.RenderAsJson(Model)

This way you can centralize the logic for creating the JSON if you, for some reason, would like to change the logic later.

Solution 7 - .Net

Andrew had a great response but I wanted to tweek it a little. The way this is different is that I like my ModelViews to not have overhead data in them. Just the data for the object. It seem that ViewData fits the bill for over head data, but of course I'm new at this. I suggest doing something like this.

Controller

virtual public ActionResult DisplaySomeWidget(int id)
{
    SomeModelView returnData = someDataMapper.getbyid(1);
    var serializer = new JavaScriptSerializer();
    ViewData["JSON"] = serializer.Serialize(returnData);
    return View(myview, returnData);
}

View

//create base js object;
var myWidget= new Widget(); //Widget is a class with a public member variable called data.
myWidget.data= <%= ViewData["JSON"] %>;
           

What This does for you is it gives you the same data in your JSON as in your ModelView so you can potentially return the JSON back to your controller and it would have all the parts. This is similar to just requesting it via a JSONRequest however it requires one less call so it saves you that overhead. BTW this is funky for Dates but that seems like another thread.

Solution 8 - .Net

<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />

Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/

I did below and it works like charm.

<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris StephensView Question on Stackoverflow
Solution 1 - .NetDavidView Answer on Stackoverflow
Solution 2 - .NetAndrew BullockView Answer on Stackoverflow
Solution 3 - .NetWolfgangView Answer on Stackoverflow
Solution 4 - .NetPharabusView Answer on Stackoverflow
Solution 5 - .NetPriya PayyavulaView Answer on Stackoverflow
Solution 6 - .NetsmoksnesView Answer on Stackoverflow
Solution 7 - .NetChris StephensView Answer on Stackoverflow
Solution 8 - .Netuser2330678View Answer on Stackoverflow