在cshtml页面上转换MVC4模型为javascript json对象

本文关键字:模型 javascript json 对象 MVC4 转换 cshtml | 更新日期: 2023-09-27 18:08:46

我有一个模型在我的cshtml页面,我想把这个模型转换成json对象,这样我就可以在javascript中使用这个json是在cshtml页面它自己。我用的是MVC4

我怎么能做到呢?

在cshtml页面上转换MVC4模型为javascript json对象

.NET Fiddle

你要找的是"序列化"。MVC 4使用Json。. NET默认为。语法非常容易使用。为了访问视图模型中的库,请使用

using Newtonsoft.Json;
一旦你使用了它,序列化的语法是这样的:
string json = JsonConvert.SerializeObject(someObject);

序列化字符串后,您可以在视图中使用json,如下所示:

var viewModel = @Html.Raw(json);

下面是一个更深入的例子:

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>