Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display formatted JSON in the view in ASP.NET MVC

Is there a way to format JSON to be displayed in the view? This way when I add a new property my API documentation will be updated automatically? Extra credit would be to surround certain elements with CSS to style it. I would also like to do this for XML.

class Student 
{
      static CreateEmpty()
      {
           return new Student() {
                 FirstName: 'Mike',
                 LastName: 'Flynn',
                 Classes: new List<Class>(),
                 School: new School() {
                      Name: 'High School'
                 }
           }
      }
}


<code>
@(Student.CreateEmpty().ToJSON())
</code>

to

<code>

{
     FirstName: 'Mike',
     LastName: 'Flynn',
     Classes: [],
     School: {
          Name: 'High School'
     }
}

</code>
like image 272
Mike Flynn Avatar asked Oct 02 '12 16:10

Mike Flynn


People also ask

How can show JSON data in ASP NET MVC?

If your data is stored in JSON format, the DataGrid does not require making a request for data manually. You can simply assign the URL of your JSON data storage to the dataSource property, and the DataGrid will fetch the data and display it.

How do I return JSON data to view?

How do I return JSON data in view? The Controller Action method will be called using jQuery POST function and JSON data will be returned back to the View using JsonResult class object.

How show JSON data table in HTML MVC?

Right click on Controller folder in the created MVC application, give the class name Home or as you wish and click OK. In the above controller class JsonResult method EmpDetails we have added the records into the Generic list and returning it as JSON to avoid database query for same result.


1 Answers

You could use JSON.NET which supports to control the JSON format and indent it:

<pre>
    @Html.Raw(JsonConvert.SerializeObject(Student.CreateEmpty(), Formatting.Indented))
</pre>
like image 116
Darin Dimitrov Avatar answered Oct 04 '22 08:10

Darin Dimitrov