0

I need to implement dependent drop-down lists in MVC4+Razor View. I have 3 drop-down lists: Country, State and City. All are coming from the database. So, I want to populate the Country list from the database. When I select a country, in the second drop-down list I should get associated states based on that country. And finally, in the third drop-down list I should get cities based on the selected state. I am sharing the code I have prepared.

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Employee_Mgmt_System.Models
{
public class EmployeeRegistration
{
    public List<string> country = new List<string>();
    public List<string> city = new List<string>();
    public List<string> state = new List<string>();

}

}

Controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Employee_Mgmt_System.Models;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    namespace Employee_Mgmt_System.Controllers
    {
        public class EmployeeRegistrationController : Controller
        {
    //
    // GET: /EmployeeRegistration/
    EmployeeRegistration Er = new EmployeeRegistration();
    public ActionResult EmployeeRegistration()
    {

        Er.getCountry();
        Er.getCity();
        Er.getState();
        ViewBag.countryddl = Er.country;
        ViewBag.cityddl = Er.city;
        ViewBag.stateddl = Er.state;
        return View(Er);
    }

    [HttpPost]
    public ActionResult Register(EmployeeRegistration empRegmodel)
    {
        if (ModelState.IsValid)
        {
            Er.registerEmpInfo(empRegmodel);
            return RedirectToAction("HomeScreen", "HomeScreen");
        }
        Er.getCountry();
        Er.getCity();
        Er.getState();
        ViewBag.countryddl = Er.country;
        ViewBag.cityddl = Er.city;
        ViewBag.stateddl = Er.state;
        return View("EmployeeRegistration");
            }

        }
    }

View

        @model Employee_Mgmt_System.Models.EmployeeRegistration
        @{
            ViewBag.Title = "EmployeeRegistration";
        }

        <body style="background-color:rgb(128,128,128)">
   
            @using (Html.BeginForm("Register", "EmployeeRegistration", FormMethod.Post))
            {
              @Html.ValidationSummary(true)
                <div style="color:red; text-align:center" >
                    <fieldset>
                        <legend>Validation Summary</legend>
                        @Html.ValidationMessageFor(m => m.Password)
                   <br />
                        @Html.ValidationMessageFor(m=>m.ConfirmPassword)
                        <br />
                        @Html.ValidationMessageFor(m=>m.EmailID)
                    </fieldset>
                </div>
               <br />
                <br />
          

                <div>
                  <table border="1" style=  "width:500px">
                           <tr>
                           <td style="width:200px">
                               @Html.LabelFor(m=>m.country)
                          </td>
                          <td>
                              @Html.DropDownListFor(m=>m.countryDDL, new SelectList(@ViewBag.CountryDDL),new {style="Width:300px"})
        @*                       @Html.DropDownListFor(m=>m.countryDDL, new SelectList(Model.country), new {style="Width:300px"})*@
                               </td>
                      </tr>
                       <tr>
                           <td style="width:200px">
                               @Html.LabelFor(m=>m.city)
                          </td>
                          <td style="width:300px">
                               @Html.DropDownListFor(m=>m.cityDDL, new SelectList(@ViewBag.CityDDL),new {style="Width:300px"})
                             @*  @Html.DropDownListFor(m=>m.cityDDL, new SelectList(Model.city), new  { style="Width:300px"})*@
                          </td>
                      </tr>
                       <tr>
                           <td style="width:200px">
                                @Html.LabelFor(m=>m.state)
                          </td>
                           <td style="width:300px">
                                @Html.DropDownListFor(m=>m.stateDDL, new SelectList(@ViewBag.StateDDL),new {style="Width:300px"})
                              @*  @Html.DropDownListFor(m=>m.stateDDL, new SelectList(Model.state), new  { style="Width:300px"})*@
                          </td>
                      </tr>
                  </table>
                  <input type="submit" value="Register Emp Information" style="text-align:center"/>
              </div>
   
            }

        </body>

2 Answers 2

2

This might help you. http://code.msdn.microsoft.com/Cascading-DropDownList-in-833683f9

Try to implement like example given in that tutorial.

1

I blogged about this very subject here:

http://jnye.co/Posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery

In essence it uses javascript to postback and retrieve an updated list of countries on each change.

@using (Html.BeginForm())
{
    <div>Select country:</div>
    <div>@Html.DropDownList("country", 
                            ViewBag.Countries as SelectList, 
                            "Please select", 
                            new { id = "country" })
    </div>
    <div>Select state:</div>
    <div>
        <select id="state" disabled="disabled"></select>
    </div>
    <input type="submit" value="Submit"/>
}


@section scripts
{
    <script type="text/javascript">
        $(function() {
            $('#country').on('change', function() {
                var stateDropdown = $('#state');
                //disable state drop down
                stateDropdown.prop('disabled', 'disabled');
                //clear drop down of old states
                stateDropdown.empty();

                //retrieve selected country
                var country = $(this).val();
                if (country.length > 0) {
                    // retrieve data using a Url.Action() to construct url
                    $.getJSON('@Url.Action("GetStates")', {
                        country: country
                    })
                    .done(function (data) {
                        //re-enable state drop down
                        stateDropdown.removeProp('disabled');
                        //for each returned state
                        $.each(data, function (i, state) {
                            //Create new option
                            var option = $('>option /<').html(state);
                            //append state states drop down
                            stateDropdown.append(option);
                        });
                    })
                    .fail(function (jqxhr, textStatus, error) {
                        var err = textStatus + ", " + error;
                        console.log("Request Failed: " + err);
                    });
                }
            });
        })
    </script>
}

You will of course have to update the GetDates() method to use your own datasource

public JsonResult GetStates(string country)
{
    var states = new List<string>();

    //TODO: You will need to update this code to supply your own data
    switch (country)
    {
        case "USA":
            states.Add("California");
            states.Add("Florida");
            states.Add("Ohio");
            break;
        case "UK":
            states.Add("London");
            states.Add("Essex");
            break;
        case "India":
            states.Add("Goa");
            states.Add("Punjab");
            break;
    }

    //Add JsonRequest behavior to allow retrieving states over http get
    return Json(states, JsonRequestBehavior.AllowGet);
}

A demo of this can also be found here: http://jnye.co/Demo/Jquery/cascading-dropdown-lists

1
  • Thanks for sharing your code but I used jquery and I am getting the values based on country I am getting states but you can see my code I have all dropdownlist ...how to bind second dropdown on POST action
    – Rahul
    Feb 28, 2014 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.