Formatting Json data in a MVC View

A quick tip on how to prettify Json data when displaying it in a .Net Core MVC view.

In the controller add a reference to the following;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Then use the following to format the Json data:

ViewBag.JsonData = JValue.Parse(data).ToString(Formatting.Indented);

Finally in the view, output the data using the HTML.Raw and enclosing it <pre> tags:

<pre>@Html.Raw(ViewBag.JsonData)</pre>

This will give the following output (based on the standard Bootstrap theme that is used in default .Net Core project template):

JsonFormat

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s