如何从 JavaScript 中的 Razor 模型对象获取 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26344089/
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
How to get JSON object from Razor Model object in javascript
提问by dsi
In viewmodel object, below is the property:
在 viewmodel 对象中,以下是属性:
public IList<CollegeInformationDTO> CollegeInformationlist { get; set; }
In VIEW, javascript is as follow:
在VIEW中,javascript如下:
var obj = JSON.stringify('@Model.CollegeInformationlist');
alert(obj[1].State); //NOT WORKING, giving string char
$.each('@Model.CollegeInformationlist', function (i, item) {
var obj = JSON.stringify(item);
var r = $.parseJSON(obj);
alert(r.State); //just giving undefined.
});
Please guide here, how i can get JSON object in javascript.
请在此处指导,我如何在 javascript 中获取 JSON 对象。
回答by hutchonoid
You could use the following:
您可以使用以下内容:
var json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));
This would output the following (without seeing your model I've only included one field):
这将输出以下内容(没有看到您的模型,我只包含了一个字段):
<script>
var json = [{"State":"a state"}];
</script>
AspNetCore
AspNetCore
AspNetCore uses Json.Serializeintead of Json.Encode
AspNetCore使用Json.Serialize这一翻译的Json.Encode
var json = @Html.Raw(Json.Serialize(@Model.CollegeInformationlist));
MVC 5/6
MVC 5/6
You can use Newtonsoft for this:
您可以为此使用 Newtonsoft:
@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model,
Newtonsoft.Json.Formatting.Indented))
This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.
这使您可以更好地控制 json 格式,即如上缩进、驼峰式等。
回答by Rob Mensching
In ASP.NET Core the IJsonHelper.Serialize()returns IHtmlContentso you don't need to wrap it with a call to Html.Raw().
在 ASP.NET Core 中,IJsonHelper.Serialize()返回,IHtmlContent因此您无需通过调用Html.Raw().
It should be as simple as:
它应该很简单:
<script>
var json = @Json.Serialize(Model.CollegeInformationlist);
</script>
回答by Frederico Martins
After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));
使用代码后var json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json));
你需要使用JSON.parse(JSON.stringify(json));
回答by Aryan Firouzian
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
将对象从控制器传递给视图,将其转换为没有编码的标记,然后将其解析为 json。
@model IEnumerable<CollegeInformationDTO>
@section Scripts{
<script>
var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
</script>
}

