Cascading DropDownList In jqGrid Using MVC

Introduction

This article will help you to understand building cascading dropdownlist in jqGrid, using MVC Application. jqGrid is the component written in JavaScript, which is more powerful and gives most of the features similar to GridView in ASP.NET.

In this article, I have created an Application, where I am getting the data from my model data. From the class List object (we can use database instead of it) bind the data to jqGrid, and the grid has an option to edit the selected row. Here, we have country and city columns , where city depends on the country.

Steps to create the project are given below-

  1. Create MVC project in Visual Studio and select empty template.





  2. Add Controller (jqGridCustomer) to the project. The control is the starting point in MVC Application. It contains the actions to Get/Post the data and display, using view.



  3. Create a view from the Index actions to display the customer data in view. Here, we are going to select empty template, as we are going to implement HTML code on our own.





  4. Install jqGrid libraries from Manage NewGet packages.







  5. Add the code, given below, in Index.html page. Here, we have added all JS files, which are related to jQuery, jqGrid and its styles. Also, add the table and div to bind the grid data and its pagination.

    Index.html
    1. @{  
    2.     ViewBag.Title = "Index";  
    3. }  
    4.   
    5. <h2>Index</h2>  
    6. <script src="~/Scripts/jquery.jqGrid.js"></script>  
    7. <script src="~/Scripts/i18n/grid.locale-en.js"></script>  
    8. <script src="~/Scripts/jquery-ui-1.12.0.js"></script>  
    9. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">   
    10. <script src="~/Scripts/ProjectCustomJS/JQLinkedDDL.js"></script>  
    11.   
    12. <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />  
    13. <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />  
    14.   
    15.       
    16. <div style="margin-left:20px">  
    17.     <table id="jqGrid"></table>  
    18.     <div id="jqGridPager"></div>  
    19. </div>  
  6. Create custom list data with few customer records. We are going to display these details in jqGrid. This is just like in memory data (we can use the database connection data also).
    1. public class LCustomerDetails  
    2. {  
    3.     public string CustomerID { get; set; }  
    4.     public string CompanyName { get; set; }  
    5.     public string Phone { get; set; }        
    6.     public string Country { get; set; }  
    7.     public string City { get; set; }  
    8. }  
    9. public class CustomerDetails  
    10. {  
    11.     public List<LCustomerDetails> GetCustomerDetails()  
    12.     {  
    13.         List<LCustomerDetails> customers = new List<LCustomerDetails>  
    14.             {  
    15.                 new LCustomerDetails(){ CustomerID = "1001", CompanyName="Ramakrishna Corp", Phone="333-23542634",   
    16.                     Country="UK",City="London"},  
    17.                 new LCustomerDetails(){ CustomerID = "1002", CompanyName="Shivakumar Corp", Phone="777-3453434",   
    18.                     Country="UK",City="Chshent"},  
    19.                 new LCustomerDetails(){ CustomerID = "1003", CompanyName="Ravindra Corp", Phone="3453434-345",   
    20.                     Country="UK",City="Welwyn Garden City"},  
    21.                 new LCustomerDetails(){ CustomerID = "1004", CompanyName="Praveenkumar Corp", Phone="9849098490",   
    22.                     Country="India",City="Hyderabad"},  
    23.                 new LCustomerDetails(){ CustomerID = "1005", CompanyName="Prashant Corp", Phone="9848098480",   
    24.                     Country="India",City="Banalore"},  
    25.                 new LCustomerDetails(){ CustomerID = "1006", CompanyName="Rakesh Corp", Phone="9848098480",   
    26.                     Country="India",City="Pune"},  
    27.                 new LCustomerDetails(){ CustomerID = "1007", CompanyName="Puneeth Corp", Phone="333-345343",   
    28.                     Country="USA",City="Chicago"},  
    29.                 new LCustomerDetails(){ CustomerID = "1008", CompanyName="Indraneel Corp", Phone="333-869232",   
    30.                     Country="USA",City="Houston"},  
    31.                 new LCustomerDetails(){ CustomerID = "1008", CompanyName="Neelohith Corp", Phone="333-456432",   
    32.                     Country="USA",City="Phoenix"},  
    33.             };           
    34.         return customers;  
    35.     }  
    36. }     
  7. Add actions in the controller to retrieve the customer details from memory custom list data and cities, based on the country selection.
    1. CustomerDetails custObj = new CustomerDetails();  
    2.   
    3. public ActionResult GetCustDetails(string sidx, string sord, int page, int rows)  
    4. {  
    5.     var cDetails = custObj.GetCustomerDetails();  
    6.     var custDetails = cDetails.Select(  
    7.             a => new  
    8.             {  
    9.                 a.CustomerID,  
    10.                 a.CompanyName,  
    11.                 a.Country,  
    12.                 a.City,  
    13.                 a.Phone   
    14.             });  
    15.     int pageIndex = Convert.ToInt32(page) - 1;  
    16.     int pageSize = rows;  
    17.     int totalRecords = custDetails.Count();  
    18.     var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);  
    19.   
    20.     var jsonData = new  
    21.     {  
    22.         total = 48,  
    23.         page,  
    24.         records = 100,  
    25.         rows = custDetails  
    26.   
    27.     };  
    28.     return Json(jsonData, JsonRequestBehavior.AllowGet);  
    29. }  
    30.   
    31. public ActionResult GetCities(string country)  
    32. {  
    33.     var cities = (from cust in custObj.GetCustomerDetails()  
    34.                     where cust.Country == country  
    35.                     select new { City = cust.City }).Distinct();  
    36.   
    37.     return Json(cities.ToList(), JsonRequestBehavior.AllowGet);  
    38. }  
  8. Create custom JS file to bind the customer details to the grid table.
    1. $(document).ready(function () {  
    2.     $("#jqGrid").jqGrid({  
    3.         // Controller Name/Action Name  
    4.         url: '/JqGridCustomer/GetCustDetails',  
    5.         datatype: "json",  
    6.   
    7.         // Column names and its properties  
    8.         colModel: [  
    9.             {  
    10.                 label: 'Customer ID',  
    11.                 name: 'CustomerID',  
    12.                 width: 75,  
    13.                 key: true  
    14.             },  
    15.             {  
    16.                 label: 'Company Name',  
    17.                 name: 'CompanyName',  
    18.                 width: 200,  
    19.                 editable: true   
    20.             },  
    21.             {  
    22.                 label: 'Phone',  
    23.                 name: 'Phone',  
    24.                 width: 200,  
    25.                 editable: true  
    26.             },             
    27.             {  
    28.                 name: 'Country',  
    29.                 width: 100,  
    30.                 editable: true,  
    31.                 edittype: "select",  
    32.                 editoptions: {  
    33.                     value: "USA:USA;UK:UK;India:India"  
    34.                 }  
    35.             },            
    36.             {  
    37.                 name: 'City',  
    38.                 width: 200,  
    39.                 editable: true,  
    40.                 edittype: "select",  
    41.                 editoptions: {  
    42.                     value: "Select a City"  
    43.                 }  
    44.             }  
    45.         ],  
    46.         jsonReader: {  
    47.             root: "rows",  
    48.             page: "page",  
    49.             total: "total",  
    50.             records: "records",  
    51.             repeatitems: false,  
    52.             Id: "0"  
    53.         },  
    54.         loadonce: true,  
    55.         viewrecorde: true,  
    56.         width: 780,  
    57.         height: 200,  
    58.         rowNum: 10,  
    59.         pager: "#jqGridPager"  
    60.     });  
    61.   
    62.     // Grid options to Enable/Disable Edit, Add, Del etc..  
    63.     $('#jqGrid').navGrid('#jqGridPager',  
    64.         // the buttons to appear on the toolbar of the grid  
    65.         { edit: true, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false },  
    66.         // options for the Edit Dialog  
    67.         {  
    68.             width: 450,  
    69.             editCaption: "The Edit Dialog",  
    70.             recreateForm: true,  
    71.             closeAfterEdit: true,  
    72.             viewPagerButtons: false,  
    73.             afterShowForm: populateCities,  
    74.             errorTextFormat: function (data) {  
    75.                 return 'Error: ' + data.responseText  
    76.             }  
    77.         },  
    78.         // options for the Add Dialog  
    79.         {  
    80.             closeAfterAdd: true,  
    81.             recreateForm: true,  
    82.             errorTextFormat: function (data) {  
    83.                 return 'Error: ' + data.responseText  
    84.             }  
    85.         },  
    86.         // options for the Delete Dailog  
    87.         {  
    88.             errorTextFormat: function (data) {  
    89.                 return 'Error: ' + data.responseText  
    90.             }  
    91.         });  
    92.   
    93.     // This function gets called whenever an edit dialog is opened  
    94.     function populateCities() {  
    95.         // first of all update the city based on the country                 
    96.         updateCityCallBack($("#Country").val(), true);  
    97.         // then hook the change event of the country dropdown so that it updates cities all the time  
    98.         $("#Country").bind("change"function (e) {  
    99.             updateCityCallBack($("#Country").val(), false);  
    100.         });  
    101.     }  
    102.   
    103.     function updateCityCallBack(country, setselected) {  
    104.         var current = $("#jqGrid").jqGrid('getRowData', $("#jqGrid")[0].p.selrow).City;  
    105.         
    106.         var countryVal = $("#Country").val();  
    107.         $("#City")  
    108.              .html("<option value=''>Loading cities...</option>")  
    109.              .attr("disabled""disabled");  
    110.   
    111.         $.ajax({  
    112.             url: '/JqGridCustomer/GetCities',  
    113.             type: "GET",  
    114.             dataType: "JSON",  
    115.             async: false,  
    116.             data: { country: countryVal },  
    117.             success: function (cities) {  
    118.                 $("#City").html(""); // clear before appending new list   
    119.                 $.each(cities, function (i, city) {  
    120.                     $("#City").append(  
    121.                         $('<option></option>').val(city.City).html(city.City));  
    122.                 });  
    123.                 $("#City").prop("disabled"false);  
    124.                 $("#City").val(current);  
    125.             }  
    126.         });  
    127.     }  
    128. });  
  9. Set the project starting point details in Route Config file.
    1. public static void RegisterRoutes(RouteCollection routes)  
    2. {  
    3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
    4.   
    5.     routes.MapRoute(  
    6.         name: "Default",  
    7.         url: "{controller}/{action}/{id}",  
    8.         defaults: new { controller = "JqGridCustomer", action = "Index", id = UrlParameter.Optional }  
    9.     );  
    10. }  
  10. Execute the project and you can see the customer details in jqGrid.



  11. Select the particular row and click Edit icon and you can edit the selected items. Here, the country and city are shown as dropdownlist and the cities will change, based on the country selection.




Hope, this article will help in understanding, how to bind the data, using jqGrid and cascading dropdownlist. Please post your comments and questions. Happy coding!!

Up Next
    Ebook Download
    View all
    Learn
    View all