Click here to Skip to main content
15,884,537 members
Articles / Web Development / HTML5

Master Detail Grid in Asp.net Mvc5

Rate me:
Please Sign up or sign in to vote.
4.47/5 (4 votes)
23 Mar 2017CPOL2 min read 18K   914   3   1
The purpouse of this article is to explain how to show data in a Nested Grid in Asp.net Mvc5, because Often we face the challenge to show data in Master - Detail way.

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.

Image 1

Step 1

Create a class called Company with the next fields :

C++
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.
C++
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.
C++
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');
        }
    });
}

 

C++
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.

Image 2

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Uruguay Uruguay
I am Software Developer with a passion for technology with strong backend (PHP, MySQL, PostgreSQL and SQL Server) and frontend (HTML5, CSS3, AngularJs and KnockOutJs) experience. I combine my education with expertise in CSS3, HTML5, Javascript to build creative and effective websites and applications.

If you wish to contact me then please do so on ricardojavister@gmail.com or feel free to skype me on
ricardo-torres-torres.

Comments and Discussions

 
QuestionNicely done! Pin
Member 127154699-Sep-17 7:55
Member 127154699-Sep-17 7:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.