Quick layout using pre-defined Json Data

Let’s say we are manually creating Json Data and use ASP.NET Core to quickly come up with a layout. This is the data (JSON output) and final outcome that we expect;

# JSON output

[ { "text": "Head Office", "nodes": [ { "text": "Finance Division", "href": "#parent1", "tags": [ "4" ], "nodes": [ { "text": "Accounting functions", "href": "#child1", "tags": [ "2" ], "nodes": [ { "text": "205", "href": "#grandchild1", "tags": [ "0" ] }, { "text": "206", "href": "#grandchild2", "tags": [ "0" ] } ] }, { "text": "Customer Invoicing", "nodes": [ { "text": 205 }, { "text": 206 } ] }, { "text": "Vendor Invoicing", "nodes": [ { "text": 205 }, { "text": 206 } ] }, { "text": "Banking relationship", "nodes": [ { "text": 205 }, { "text": 206 } ] } ] } ] } ]

Create your test data and drop it under Models, call it DummyData.json. Make sure it’s a valid JSON. These are the lines that we need in controller action method;

var folderDetails = Path.Combine(Directory.GetCurrentDirectory(), $"Models\\{"DummyData.json"}");
var JSON = System.IO.File.ReadAllText(folderDetails);
ViewBag.defaultData = JSON;

return View(result);

In the view, we are rendering ViewBag values in a div HTML tag;

<div id="layoutData">@(ViewBag.defaultData)</div>

We are using jQuery to read this data and use it in any control;

var layoutData = $('#layoutData').text();

You can use layoutData variable anywhere you want. Make sure you are not vulnerable to XSS attacks. For XSS attacks, read this

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect