3

I have a model in my cshtml page and I want to covert this model into json object so that I may use this json in javascript that is on cshtml page it self. I am using MVC4.

How I can do that?

  • 1
    You can use [`Json.Encode()`](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode.aspx) as described in [How do I write unencoded Json to my View using Razor?](http://stackoverflow.com/questions/4072762/how-do-i-write-unencoded-json-to-my-view-using-razor) – Jonathan Lonowski Jun 13 '14 at 20:23
  • @JonathanLonowski - That is deprecated. MVC 4 uses `JsonConvert.SerializeObject` – Travis J Jun 13 '14 at 20:45
  • @TravisJ Where is it documented as deprecated? The [namespace](http://msdn.microsoft.com/en-us/library/system.web.helpers.aspx) and [class](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.aspx) don't list it as "Obsolete." – Jonathan Lonowski Jun 13 '14 at 20:49
  • @JonathanLonowski - I was mistaken. It is not deprecated. I thought that it was still using JavaScriptSerializer but it turns out that it uses the default Json serializer which is Json.NET in mvc4 so that all works out. – Travis J Jun 13 '14 at 20:56

1 Answers1

8

.NET Fiddle

What you are looking for is called "Serialization". MVC 4 uses Json.NET by default. The syntax is very easy to use. In order to have access to the library in your view model, use

using Newtonsoft.Json;

Once you have used that, the syntax for serializing is like this:

string json = JsonConvert.SerializeObject(someObject);

After serializing the string, you may use the json in your view like this:

var viewModel = @Html.Raw(json);

Here is a more in depth example:

Model.cs

public class SampleViewModel : AsSerializeable
{
    public string Name { get; set; }
    public List<NestedData> NestedData { get; set; }
    public SampleViewModel()
    {
        this.Name = "Serialization Demo";
        this.NestedData = Enumerable.Range(0,10).Select(i => new NestedData(i)).ToList();   
    }
}

public class NestedData
{
    public int Id { get; set; }
    public NestedData(int id)
    {
        this.Id = id;   
    }
}

public abstract class AsSerializeable
{
    public string ToJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}

Controller.cs

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new SampleViewModel());
    }
}    

View.cshtml

    <body>
    <div>
        <h1 id="Name"></h1>
        <div id="Data"></div>
    </div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    //Load serialized model
    var viewModel = @Html.Raw(Model.ToJson());

    //use view model
    $("#Name").text(viewModel.Name);

    var dataSection = $("#Data");
    $.each(viewModel.NestedData,function(){
        dataSection.append("<div>id: "+this.Id+"</div>");
    });
</script>
Travis J
  • 81,153
  • 41
  • 202
  • 273