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. <h2>Index</h2>
    5. <script src="~/Scripts/jquery.jqGrid.js"></script>
    6. <script src="~/Scripts/i18n/grid.locale-en.js"></script>
    7. <script src="~/Scripts/jquery-ui-1.12.0.js"></script>
    8. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    9. <script src="~/Scripts/ProjectCustomJS/JQLinkedDDL.js"></script>
    10. <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
    11. <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    12. <div style="margin-left:20px">
    13. <table id="jqGrid"></table>
    14. <div id="jqGridPager"></div>
    15. </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. public ActionResult GetCustDetails(string sidx, string sord, int page, int rows)
    3. {
    4. var cDetails = custObj.GetCustomerDetails();
    5. var custDetails = cDetails.Select(
    6. a => new
    7. {
    8. a.CustomerID,
    9. a.CompanyName,
    10. a.Country,
    11. a.City,
    12. a.Phone
    13. });
    14. int pageIndex = Convert.ToInt32(page) - 1;
    15. int pageSize = rows;
    16. int totalRecords = custDetails.Count();
    17. var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
    18. var jsonData = new
    19. {
    20. total = 48,
    21. page,
    22. records = 100,
    23. rows = custDetails
    24. };
    25. return Json(jsonData, JsonRequestBehavior.AllowGet);
    26. }
    27. public ActionResult GetCities(string country)
    28. {
    29. var cities = (from cust in custObj.GetCustomerDetails()
    30. where cust.Country == country
    31. select new { City = cust.City }).Distinct();
    32. return Json(cities.ToList(), JsonRequestBehavior.AllowGet);
    33. }
  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. // Column names and its properties
    7. colModel: [
    8. {
    9. label: 'Customer ID',
    10. name: 'CustomerID',
    11. width: 75,
    12. key: true
    13. },
    14. {
    15. label: 'Company Name',
    16. name: 'CompanyName',
    17. width: 200,
    18. editable: true
    19. },
    20. {
    21. label: 'Phone',
    22. name: 'Phone',
    23. width: 200,
    24. editable: true
    25. },
    26. {
    27. name: 'Country',
    28. width: 100,
    29. editable: true,
    30. edittype: "select",
    31. editoptions: {
    32. value: "USA:USA;UK:UK;India:India"
    33. }
    34. },
    35. {
    36. name: 'City',
    37. width: 200,
    38. editable: true,
    39. edittype: "select",
    40. editoptions: {
    41. value: "Select a City"
    42. }
    43. }
    44. ],
    45. jsonReader: {
    46. root: "rows",
    47. page: "page",
    48. total: "total",
    49. records: "records",
    50. repeatitems: false,
    51. Id: "0"
    52. },
    53. loadonce: true,
    54. viewrecorde: true,
    55. width: 780,
    56. height: 200,
    57. rowNum: 10,
    58. pager: "#jqGridPager"
    59. });
    60. // Grid options to Enable/Disable Edit, Add, Del etc..
    61. $('#jqGrid').navGrid('#jqGridPager',
    62. // the buttons to appear on the toolbar of the grid
    63. { edit: true, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
    64. // options for the Edit Dialog
    65. {
    66. width: 450,
    67. editCaption: "The Edit Dialog",
    68. recreateForm: true,
    69. closeAfterEdit: true,
    70. viewPagerButtons: false,
    71. afterShowForm: populateCities,
    72. errorTextFormat: function (data) {
    73. return 'Error: ' + data.responseText
    74. }
    75. },
    76. // options for the Add Dialog
    77. {
    78. closeAfterAdd: true,
    79. recreateForm: true,
    80. errorTextFormat: function (data) {
    81. return 'Error: ' + data.responseText
    82. }
    83. },
    84. // options for the Delete Dailog
    85. {
    86. errorTextFormat: function (data) {
    87. return 'Error: ' + data.responseText
    88. }
    89. });
    90. // This function gets called whenever an edit dialog is opened
    91. function populateCities() {
    92. // first of all update the city based on the country
    93. updateCityCallBack($("#Country").val(), true);
    94. // then hook the change event of the country dropdown so that it updates cities all the time
    95. $("#Country").bind("change", function (e) {
    96. updateCityCallBack($("#Country").val(), false);
    97. });
    98. }
    99. function updateCityCallBack(country, setselected) {
    100. var current = $("#jqGrid").jqGrid('getRowData', $("#jqGrid")[0].p.selrow).City;
    101. var countryVal = $("#Country").val();
    102. $("#City")
    103. .html("<option value=''>Loading cities...</option>")
    104. .attr("disabled", "disabled");
    105. $.ajax({
    106. url: '/JqGridCustomer/GetCities',
    107. type: "GET",
    108. dataType: "JSON",
    109. async: false,
    110. data: { country: countryVal },
    111. success: function (cities) {
    112. $("#City").html(""); // clear before appending new list
    113. $.each(cities, function (i, city) {
    114. $("#City").append(
    115. $('<option></option>').val(city.City).html(city.City));
    116. });
    117. $("#City").prop("disabled", false);
    118. $("#City").val(current);
    119. }
    120. });
    121. }
    122. });
  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. routes.MapRoute(
    5. name: "Default",
    6. url: "{controller}/{action}/{id}",
    7. defaults: new { controller = "JqGridCustomer", action = "Index", id = UrlParameter.Optional }
    8. );
    9. }
  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!!