Introduction
This example let us explore the power of jQuery to retrieve data from Server Side to Client Side, additional we are going to study the JsonResult class that let us serialize an object into a Json Response.
Background
It´s important that before to go throught this topic, review this previous topics:
JsonResult: Serializes the objects it is given into JSON and writes the JSON to the response, typically in response to an Ajax request.
The JsonResult uses the JavaScriptSerializer class to serialize its contents (specified via the Data property) to the JSON (JavaScript Object Notation) format. This is useful for Ajax scenarios that have a need for an action method to return data in a format easily consumable by JavaScript.
As for ContentResult, the content encoding and content type for the JsonResult can both be set via properties. The only difference is that the default ContentType is application/json and not text/html for this result.
jQuery has become essential in the world of web development, because jQuery has the proven capability to reduce many lines of ordinary JavaScript to just a few lines.
Using the code
This code demostrates how to retrieve data from a Controller , that exposes a method that shows a Json respose to be consumed for an Ajax Request.
Step 1
Create a class called Company with the next fields :
namespace NestedGridFromJson.Models
{
public class Company
{
public string name { get; set; }
public string bio { get; set; }
public string headquarter { get; set; }
public string[] details { get; set; }
}
}
Step 2
Create a controller called HomeController with two methods :
- GetCompaniesData : Retrieve the list of Companies that are coming from GetCompanies method to convert in a Json Response.
- GetCompanies: Returns a List of Companies.
public JsonResult GetCompaniesData()
{
var users = GetCompanies();
return Json(GetCompanies(), JsonRequestBehavior.AllowGet);
}
private List<Company> GetCompanies() {
var companiesList = new List<Company>
{
new Company { name ="Walmart", bio ="Retailer", headquarter="Bentonville, Arkansas",
details = new string[] { "Number of WallMart employees : 2.2 million", "Population of Slovenia : 2.1 million", "Annual Revenue : $486 billion (2015)" }
},
new Company { name ="Apple", bio ="Tech Company", headquarter="Cupertino, California",
details = new string[] { "Apple's economic output (2014): $87 billion", "Oman's annual GDP (2014): $82 billion", "Annual Revenue : $234 billion (2015)" }
},
new Company { name ="Microsoft", bio ="Tech Company", headquarter="RedMond, Washington",
details = new string[] { "Annual Revenue: $94 billion (2015)", "Microsoft Office: 1.2 billion users", "107 Language spoken" }
}
};
return companiesList;
}
Step 3
Create a file main.js that will be on charge to make the request against the method GetCompaniesData to retrieve data in Json format.
This file is separated in two methods :
- initOpenAndCloseDetails : Responsible to control the events to open and close the details div.
- initGetData : Responsible to provide functionality to the button btnGetData in the click event. Basically when user clicks this button, it is going to make an Ajax Request to the Controller HomeController to retrieve the data, after of that, each record retrieved is going to be used to create a new row with Master and Detail Information.
function initOpenAndCloseDetails() {
$('#grid1 div').click(function () {
if ($(this).attr('class') == 'collapsed') {
$(this).attr('class', 'expanded');
var ul = $(this).parent().parent().closest('tr').next('tr').find('.details-opened').removeClass('details-opened');
$(ul).addClass('details-closed');
} else {
$(this).attr('class', 'collapsed');
var ul = $(this).parent().parent().closest('tr').next('tr').find('.details-closed').removeClass('details-closed');
$(ul).addClass('details-opened');
}
});
}
function initGetData() {
$('#btnGetData').click(function () {
$("#grid1").find("tr:gt(0)").remove();
var request = new XMLHttpRequest();
request.open('GET', '../home/GetCompaniesData', true);
request.onload = function () {
if (request.status == 200) {
var myStuff = JSON.parse(request.responseText);
console.log(myStuff);
var i=0;
var grid1 = $('#grid1');
while (i <= myStuff.length - 1) {
var obj = myStuff[i];
var addresslist = '';
var li = ''
var j = 0;
while (j <= obj.details.length - 1) {
li = li + "<li>" + obj.details[j] + "</li>";
j++;
}
addresslist = "<tr><td colspan=4><ul class='details-closed'>" + li + "</ul></td></tr>";
grid1.append('<tr><td><div class=expanded id=' + i + '></div></td><td>' + obj.name + '</td><td>' + obj.bio + '</td><td>' + obj.headquarters + '</td></tr>' + addresslist);
i++;
}
initOpenAndCloseDetails();
}
}
request.send();
});
}
initGetData();
You will find very useful this way to retrieve Data not just to show a Master Detail Data in a table but also to show data in any Html Object, for instance : lists, dropdownlist, checkbox, etc.
Conclusion
Combine the power of Jquery to make asynchronous requests to server joined with the capacity of JsonResult Class to serialize an object into a Json response give us a great flexibility to design efficient methods in Controller.
Please, download the code above and let me know if you have any question about it, I will appreciatte your comments!
History
1st Version