How to get JSON object from Razor Model object in javascript

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

In viewmodel object, below is the property:

  public IList CollegeInformationlist { get; set; }

In VIEW, javas

相关标签:
5条回答
  • 2020-12-02 08:45

    After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

    You need use JSON.parse(JSON.stringify(json));

    0 讨论(0)
  • 2020-12-02 08:50

    Pass the object from controller to view, convert it to markup without encoding, and parse it to json.

    @model IEnumerable<CollegeInformationDTO>
    
    @section Scripts{
        <script>
              var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
        </script>
    }
    
    0 讨论(0)
  • 2020-12-02 08:56

    If You want make json object from yor model do like this :

      foreach (var item in Persons)
       {
        var jsonObj=["FirstName":"@item.FirstName"]
       }
    

    Or Use Json.Net to make json from your model :

    string json = JsonConvert.SerializeObject(person);
    
    0 讨论(0)
  • 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):

    <script>
        var json = [{"State":"a state"}];   
    </script>
    

    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.

    0 讨论(0)
  • 2020-12-02 09:05

    In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

    It should be as simple as:

    <script>
      var json = @Json.Serialize(Model.CollegeInformationlist);
    </script>
    
    0 讨论(0)
提交回复
热议问题