Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  89] [ 7]  / answers: 1 / hits: 136475  / 10 Years ago, mon, october 13, 2014, 12:00:00

In viewmodel object, below is the property:



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


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


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


More From » asp.net

 Answers
25

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.


[#69137] Friday, October 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;