106

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.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
dsi
  • 3,199
  • 12
  • 59
  • 102
  • your javascript doesn't know what your CollegeInformationDTO class looks like. At my last job we defined an object in the script with the same structure as the model and then did a jquery .map to map the model to the javascript object. Also make sure what you are passing to the view is a JSON string – Matt Bodily Oct 13 '14 at 15:58
  • You need to serialise your Model object to JSON. You should create a method (or property) that returns that result. – musefan Oct 13 '14 at 16:00
  • Can you please share me some stuff to do this. here, i wrote `var obj = JSON.stringify('@Model.CollegeInformationlist');` so, it should convert to JSON object and able to give result when explicitly write `.State` property but, its not working like a way. It looks, OBJECT is converted to string type. – dsi Oct 13 '14 at 16:05

6 Answers6

230

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.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • I could not find JSON reference, getting an error as `The name 'Json' does not exist in the current context ` If i add, `Newtonsoft.Json.` then, `Encode` not found. – dsi Oct 13 '14 at 16:20
  • @dhaval http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx – hutchonoid Oct 13 '14 at 17:47
  • 21
    For anyone using AspNetCore, that uses `Json.Serialize` instead of `Json.Encode`. – TrueWill May 10 '17 at 14:49
  • 6
    For newer versions of MVC 5/6 `@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented))` – Lord Darth Vader Jul 14 '17 at 12:17
  • 1
    @R2D2 an added spin on your suggestion: `JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })` this also insures proper JavaScript CamelCase (or I should say `camelCase`) for the serialized JSON. – Al Dass Mar 13 '18 at 02:46
  • 2
    @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented)) worked for me – smj May 09 '18 at 02:37
  • If the json object contains string values that contain html markup inside them, this will break the page. – Thanasis Ioannidis Feb 08 '19 at 11:12
  • A solution that is safe for XSS attacks? – Marius Vuscan Jul 30 '20 at 12:44
  • XSS attacks solution: https://stackoverflow.com/questions/4072762/how-do-i-write-unencoded-json-to-my-view-using-razor – Marius Vuscan Jul 30 '20 at 12:59
  • @Marius98 The MVC 5/6 Newtonsoft example above. The XSS risk is increased if the model that is eventually serialized has came from the client or an external source too. – hutchonoid Jul 31 '20 at 09:34
  • Note for potential readers, you need to include a using statement for both Newtonsoft.Json and Newtonsoft.Json.Serialization to use JsonConvert.SerializeObject(); (for MVC5+) – Kim Skogsmo Jan 15 '22 at 12:41
21

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>
Rob Mensching
  • 33,834
  • 5
  • 90
  • 130
4

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

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

  • Small thing but you should format your code segment on the second line. It's too small of an edit so it won't let me do it. – Michael Apr 06 '18 at 18:11
  • Why would you `JSON.stringify` and `JSON.parse` right one after another? It wouldn't be needed and would waste the resources. – Peter Ivan Nov 18 '19 at 10:20
  • Make sense. I need test if work without JSON.stringify. I think that just `JSON.parse(@Html.Raw(Json.Encode(@Model.CollegeInformationlist)))` should work. Someone can test and let us know. But now I use that way and work to me. – Frederico Martins Nov 29 '19 at 19:06
2

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>
}
Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
  • Why would you wrap the result in quotes and `JSON.parse` right one after another? It wouldn't be needed and would waste the resources. – Peter Ivan Nov 18 '19 at 10:21
1

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);
M.Azad
  • 3,673
  • 8
  • 47
  • 77
0

The following code worked for me

var chartD =  JSON.parse(JSON.stringify([@Json.Serialize(@Model)]));
cigien
  • 57,834
  • 11
  • 73
  • 112
Lishani
  • 57
  • 6