<分区>
我的 cshtml 页面中有一个模型,我想将这个模型转换为 json 对象,这样我就可以在 cshtml 页面上的 javascript 中使用这个 json。我正在使用 MVC4。
我该怎么做?
<分区>
我的 cshtml 页面中有一个模型,我想将这个模型转换为 json 对象,这样我就可以在 cshtml 页面上的 javascript 中使用这个 json。我正在使用 MVC4。
我该怎么做?
最佳答案
您正在寻找的是所谓的“序列化”。 MVC 4 默认使用 Json.NET。语法非常易于使用。为了访问 View 模型中的库,请使用
using Newtonsoft.Json;
一旦你使用了它,序列化的语法就像这样:
string json = JsonConvert.SerializeObject(someObject);
序列化字符串后,您可以像这样在 View 中使用 json:
var viewModel = @Html.Raw(json);
这是一个更深入的例子:
模型.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>
关于c# - 将 MVC4 模型转换为 cshtml 页面上的 javascript json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213224/