CSharp · Mvc
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
namespace HelloWorldMvcApp
{
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);
}
}
}
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
</head>
<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>
</html>
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
}
}