如何从 JavaScript 中的 Razor 模型对象获取 JSON 对象 [英] How to get JSON object from Razor Model object in javascript

查看:32
本文介绍了如何从 JavaScript 中的 Razor 模型对象获取 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在viewmodel对象中,下面是属性:

In viewmodel object, below is the property:

  public IList<CollegeInformationDTO> CollegeInformationlist { get; set; }

在VIEW中,javascript如下:

In VIEW, javascript is as follow:

   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.
    });

请在此处指导,我如何在 javascript 中获取 JSON 对象.

Please guide here, how i can get JSON object in javascript.

推荐答案

您可以使用以下内容:

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 使用 Json.Serialize 而不是 Json.Encode

AspNetCore uses Json.Serialize intead of Json.Encode

var json = @Html.Raw(Json.Serialize(@Model.CollegeInformationlist));

MVC 5/6

您可以为此使用 Newtonsoft:

You can use Newtonsoft for this:

    @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, 
Newtonsoft.Json.Formatting.Indented))

这使您可以更好地控制 json 格式,即如上缩进、驼峰格式等.

This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.

这篇关于如何从 JavaScript 中的 Razor 模型对象获取 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆