How to get JSON object from Razor Model object in javascript

前端 未结 5 1798
遇见更好的自我
遇见更好的自我 2020-12-02 08:09

In viewmodel object, below is the property:

  public IList CollegeInformationlist { get; set; }

In VIEW, javas

5条回答
  •  无人及你
    2020-12-02 09:03

    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):

    
    

    Working Fiddle

    AspNetCore

    AspNetCore uses Json.Serialize intead of Json.Encode

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

    MVC 5/6

    You can use Newtonsoft for this:

        @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.

提交回复
热议问题