ASP.NET MVC – Convert Model to JSON in Javascript

  • by
mvc-model-json-object-javascript-01

In this post we will convert ASP.NET MVC Razor Model object into JSON inside javascript code. We will be using a simple Model class object with Product information and passing it to MVC View. Inside our View page we will convert razor Model to JSON object and use it to filter HTML table. You can simply convert ASP.NET MVC model object into JSON object by using :

var model = @Html.Raw(Json.Encode(Model));

where Model is the model object. In this example we will use this to convert our Model object and use JSON to filter a DropDownList and a HTML table and display data accordingly.
 
DOWNLOAD SOURCE CODE

Model class – ProductInfo.class:

using System.Collections.Generic;

namespace AngularWebAPI.Models
{
public class ProductInfo
{
public string Product { get; set; }
public string Category { get; set; }
public string Price { get; set; }
public string Company { get; set; }
public List<ProductInfo> lstProducts { get; set; }
}
}

Controller – ProductInfoController.cs:

using AngularWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace AngularWebAPI.Controllers
{
public class ProductInfoController : Controller
{
// GET: ProductInfo
public ActionResult Index()
{
ProductInfo products = getProducts();
return View(products);
}

[NonAction]
public ProductInfo getProducts()
{
ProductInfo product = new ProductInfo();
try
{
product.lstProducts = new List<ProductInfo>();

product.lstProducts.Add(new ProductInfo { Category = "Car", Company="TATA", Price="695000", Product="Tata Nexon" });
product.lstProducts.Add(new ProductInfo { Category = "Car", Company = "Hyundai", Price = "670000", Product = "Hyundai Venue" });
product.lstProducts.Add(new ProductInfo { Category = "Car", Company = "Honda", Price = "975000*", Product = "Honda All City" });

product.lstProducts.Add(new ProductInfo { Category = "Bike", Company = "Royal Enfield", Price = "159824", Product = "Royal Enfield Classic 350" });
product.lstProducts.Add(new ProductInfo { Category = "Bike", Company = "Royal Enfield", Price = "124311", Product = "Royal Enfield Bullet 350" });
product.lstProducts.Add(new ProductInfo { Category = "Bike", Company = "TVS", Price = "95000", Product = "TVS Apache RTR 160" });

}
catch (Exception ex)
{

}

return product;
}

}
}

We are not using any Database source table. We will simply pass some static data to achieve our goal. On the MVC view page, we will display distinct “Category” on a DropDownList and filter the data as per the use selection and show it on a HTML table. mvc-model-json-object-javascript-01 For this, create a MVC view for our Index method.

Views > ProductInfo > Index.cshtml:

@model AngularWebAPI.Models.ProductInfo

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body style="padding:10px;">
<div>
@if (Model != null && Model.lstProducts != null && Model.lstProducts.Count > 0)
{
<span><b>Please select a Category to filter table:</b></span> <select id="selectCategory" onchange="filterTable(this.value)"></select>
<hr/>
<div id="myTable">
<table class="table table-bordered" id="tblProducts" >
<thead>
<tr>
<th>
Product
</th>
<th>
Company
</th>
<th>
Category
</th>
<th>
Price
</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.lstProducts)
{
<tr>
<td>@product.Product</td>
<td>@product.Company</td>
<td>@product.Category</td>
<td>Rs.@product.Price</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>

<script>

var model = @Html.Raw(Json.Encode(Model));
var selection = document.getElementById('selectCategory');

var myTable = document.getElementById('myTable');

var categories = [""];
var products = model.lstProducts;
for (var pro in products) {
if (!categories.includes(products[pro].Category)) {
var option = document.createElement('option');
option.value = products[pro].Category;
option.innerHTML = products[pro].Category;
categories.push(products[pro].Category);
selectCategory.appendChild(option);
}
}

function filterTable(category)
{
myTable.innerHTML = '';
var finalTable = '';
finalTable = '<table class="table table-bordered" id="tblProducts"><thead><tr><th>Product</th><th>Company</th><th>Category</th><th>Price</th></tr></thead>';

for (var product in products) {

if (products[product].Category === category) {
var pro = products[product];
finalTable += '<tr><td>' + pro.Product + '</td><td>' + pro.Company + '</td><td>' + pro.Category + '</td><td>Rs.' + pro.Price + '</td></tr>';
}
}
finalTable += '</tbody></table>';

myTable.innerHTML = finalTable;

}
</script>
</body>
</html>

The javascript will parse the Razor model object into JSON object. After this we can simply filter our List object. The JSON object will be having objects same like our Model class. So we can easily parse them and filter them. mvc-model-json-object-javascript-02
 
DOWNLOAD SOURCE CODE

Also see:

How to use JQuery Datepicker on MVC views?

ASP.NET MVC – How to create and consume REST API?

How to create a Digital Clock in Javascript?