May 12, 2016

MVC DropDownListFor fill on selection change of another dropdown

Binding DropDownListFor from enum, database and some hard coded values in our previous article MVC dropdown binding best ways. In this article we will try to bind child Dropdown on selection change of parent Dropdown, say Country to State or Sate to City, by using jQuery which will call an action in controller and return JSON for selected id, and with the help of jQuery append values to child Dropdown. We will try to create page to add new employee and state and city will be used as parent and child Dropdown.
alt text
Let's see the tables we are going to use:
  1. public partial class State
  2. {
  3.     public int StateId { get; set; }
  4.     public string StateName { get; set; }
  5.     public string Abbr { get; set; }
  6. }
  7. public partial class City
  8. {
  9.     public int CityId { get; set; }
  10.     public string CityName { get; set; }
  11.     public int StateId { get; set; }
  12. }
Employee Model:
  1. public class Employees
  2. {
  3.     [Key]
  4.     public int EmployeeId { get; set; }
  5.     [Required, Display(Name="Employee Name")]
  6.     public string EmployeeName { get; set; }
  7.     [Required, Display(Name = "Address")]
  8.     public String Address { get; set; }
  9.     [Required, Display(Name = "State")]
  10.     public int State { get; set; }
  11.     [Required, Display(Name = "City")]
  12.     public int City { get; set; }
  13.     [Display(Name = "Zip Code")]
  14.     public String ZipCode { get; set; }
  15.     [Required, Display(Name = "Phone #")]
  16.     public String Phone { get; set; }
  17. }
As you can see, I have not added anything in our model for list of states or cities because we are using Code first, which will create the database tables, we will try to get data from database and pass to view by using ViewBag, here is our HttpGet and HttpPost action method:
  1. [HttpGet]
  2. public ActionResult Create()
  3. {
  4.     ViewBag.StateList = db.States;
  5.     var model = new Employees();
  6.     return View(model);
  7. }
  8. [HttpPost]
  9. public ActionResult Create(Employees model)
  10. {
  11.     if (ModelState.IsValid)
  12.     {
  13.         // code to save record  and redirect to listing page
  14.     }
  15.     ViewBag.StateList = db.States;
  16.     return View(model);
  17. }
HTML code for both state and city dropdown:
  1. <div class="form-group">
  2.     @Html.LabelFor(m => m.State,  new { @class = "control-label col-md-2" })
  3.     <div class="col-md-10">
  4.         @Html.DropDownListFor(m => m.State,
  5.               new SelectList(ViewBag.StateList, "StateId", "StateName"),
  6.               "Select state",
  7.               new { @class = "form-control", @onchange="FillCity()" })
  8.         @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
  9.     </div>
  10. </div>
  11. <div class="form-group">
  12.     @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
  13.     <div class="col-md-10">
  14.         @Html.DropDownListFor(m => m.City,
  15.        new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
  16.               "Select city",
  17.               new { @class = "form-control" })
  18.         @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
  19.     </div>
  20. </div>
As you can notice we used @onchange="FillCity()" in our State dropdown so we need a JavaScript function which will be call on change of state. If you are from asp.net background then forgot about the postback, in mvc there is no postback concept so we don't need viewstate of controls so the pages are light weight. Here is our FillCity function:
  1. @section Scripts {
  2. <script>
  3.   function FillCity() {
  4.     var stateId = $('#State').val();
  5.     $.ajax({
  6.         url: '/Employees/FillCity',
  7.         type: "GET",
  8.         dataType: "JSON",
  9.         data: { State: stateId},
  10.         success: function (cities) {                    
  11.             $("#City").html(""); // clear before appending new list
  12.             $.each(cities, function (i, city) {
  13.                 $("#City").append(
  14.                     $('<option></option>').val(city.CityId).html(city.CityName));
  15.             });
  16.         }
  17.     });
  18.   }
  19. </script>
  20. }
Here we used $.each to loop the items and add item by item to city dropdown. We used to call FillCity action method in our Employees controller.We need a separate action method which can return cities on the basis of selection change and return JSON string.
  1. public ActionResult FillCity(int state)
  2. {
  3.     var cities = db.Cities.Where(c => c.StateId == state);
  4.     return Json(cities, JsonRequestBehavior.AllowGet);
  5. }
See how we can return json from any action method in our controller. If you want to see the complete html of the page then it is here.
  1. @model MyApp.Models.Employees
  2. @{
  3.     ViewBag.Title = "Index";
  4.     Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. <h2>Index</h2>
  7. @using (Html.BeginForm())
  8. {
  9. @Html.AntiForgeryToken()
  10. <div class="form-horizontal">
  11.     <h4>New Employee</h4>      
  12.     <div class="form-group">
  13.         @Html.LabelFor(m => m.EmployeeName, new { @class = "control-label col-md-2" })
  14.         <div class="col-md-10">
  15.             @Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control" })
  16.             @Html.ValidationMessageFor(m => m.EmployeeName, "", new { @class = "text-danger" })
  17.         </div>
  18.     </div>
  19.     <div class="form-group">
  20.         @Html.LabelFor(m => m.Address, new { @class = "control-label col-md-2" })
  21.         <div class="col-md-10">
  22.             @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
  23.             @Html.ValidationMessageFor(m => m.Address, "", new { @class = "text-danger" })
  24.         </div>
  25.     </div>
  26.     <div class="form-group">
  27.         @Html.LabelFor(m => m.State,  new { @class = "control-label col-md-2" })
  28.         <div class="col-md-10">
  29.             @Html.DropDownListFor(m => m.State,
  30.                   new SelectList(ViewBag.StateList, "StateId", "StateName"),
  31.                   "Select state",
  32.                   new { @class = "form-control", @onchange="FillCity()" })
  33.             @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
  34.         </div>
  35.     </div>
  36.     <div class="form-group">
  37.         @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
  38.         <div class="col-md-10">
  39.             @Html.DropDownListFor(m => m.City,
  40.            new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
  41.                   "Select city",
  42.                   new { @class = "form-control" })
  43.             @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
  44.         </div>
  45.     </div>
  46.     <div class="form-group">
  47.         @Html.LabelFor(m => m.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
  48.         <div class="col-md-10">
  49.             @Html.TextBoxFor(m => m.ZipCode,  new { @class = "form-control" })
  50.             @Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })
  51.         </div>
  52.     </div>
  53.     <div class="form-group">
  54.         @Html.LabelFor(m => m.Phone, new { @class = "control-label col-md-2" })
  55.         <div class="col-md-10">
  56.             @Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })
  57.             @Html.ValidationMessageFor(m => m.Phone, "", new { @class = "text-danger" })
  58.         </div>
  59.     </div>
  60.     <div class="form-group">
  61.         <div class="col-md-offset-2 col-md-10">
  62.             <input type="submit" value="Create" class="btn btn-success" />
  63.             <a href="/Employees" class="btn btn-warning" >Cancel</a>
  64.         </div>
  65.     </div>
  66. </div>
  67. }
If you want to add more column value into dropdown text you can concatenate them easily, say we want to show both Id and text in city drop down then we simmply show it like this:
$('<option></option>').
   val(city.CityId).html(city.CityId + " - " + city.CityName)); 
Whatever we see here is not complete to maintain the selected value if we found the model invalid in our post method and return back to the view then current selected state's cities will be lost same will happen when we need to fill and select the value in city dropdown for a saved records. We need to add one more JavaScript method to check on document.ready if there is any value already selected in state dropdown then call the FillCity method and fill our city dropdown and selected the city value which we get from the model.
I am leaving it for you so you can do a little bit practice, hope you will easily complete it, best of luck.

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib