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?
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?
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>