javascript 将MVC4模型转换为cshtml页面上的javascript json对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24213224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert MVC4 Model into javascript json object on cshtml page
提问by Travis J
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.
我的 cshtml 页面中有一个模型,我想将此模型转换为 json 对象,以便我可以在 cshtml 页面上的 javascript 中使用此 json。我正在使用 MVC4。
How I can do that?
我怎么能做到这一点?
回答by Travis J
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
您正在寻找的内容称为“序列化”。MVC 4 默认使用 Json.NET。语法非常易于使用。为了访问您的视图模型中的库,请使用
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:
序列化字符串后,您可以像这样在视图中使用 json:
var viewModel = @Html.Raw(json);
Here is a more in depth example:
这是一个更深入的例子:
Model.cs
模型.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
控制器.cs
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
}
View.cshtml
查看.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>