Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在cshtml页面上将MVC4模型转换为javascript json对象_C#_Javascript_Jquery_Asp.net Mvc 4 - Fatal编程技术网

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

C# 在cshtml页面上将MVC4模型转换为javascript json对象,c#,javascript,jquery,asp.net-mvc-4,C#,Javascript,Jquery,Asp.net Mvc 4,我的cshtml页面中有一个模型,我想将这个模型转换成json对象,这样我就可以在cshtml页面上的javascript中使用这个json。我正在使用MVC4 我该怎么做呢? 您正在寻找的是所谓的“序列化”。MVC4默认使用Json.NET。语法非常容易使用。要访问视图模型中的库,请使用 using Newtonsoft.Json; 一旦使用了它,序列化的语法如下所示: string json = JsonConvert.SerializeObject(someObject); var v

我的cshtml页面中有一个模型,我想将这个模型转换成json对象,这样我就可以在cshtml页面上的javascript中使用这个json。我正在使用MVC4

我该怎么做呢?

您正在寻找的是所谓的“序列化”。MVC4默认使用Json.NET。语法非常容易使用。要访问视图模型中的库,请使用

using Newtonsoft.Json;
一旦使用了它,序列化的语法如下所示:

string json = JsonConvert.SerializeObject(someObject);
var viewModel = @Html.Raw(json);
序列化字符串后,可以在视图中使用json,如下所示:

string json = JsonConvert.SerializeObject(someObject);
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);
    }
}
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>

//加载序列化模型
var viewModel=@Html.Raw(Model.ToJson());
//使用视图模型
$(“#Name”).text(viewModel.Name);
var数据部分=$(“#数据”);
$.each(viewModel.NestedData,function(){
追加(“id:+this.id+”);
});

您可以按照@JonathanLonowski中的描述使用,这是不推荐使用的。MVC4使用了
JsonConvert.SerializeObject
@TravisJ,它在哪里被记录为已弃用?请不要把它列为“过时的”。@JonathanLonowski-我错了。它没有被弃用。我原以为它仍在使用JavaScriptSerializer,但事实证明它使用了默认的Json序列化程序,即mvc4中的Json.NET,所以一切正常。我喜欢在基类上放置
ToJson()
。非常感谢。