How to get JSON object from Razor Model object in javascript
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 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.
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>
After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json))
;