SIGN UP MEMBER LOGIN:    
ARTICLE

Cascading DropDown List in ASP.NET MVC 2 using JQuery

Posted by Kumar Saurabh Articles | ASP.NET MVC with C# February 21, 2011
Here I will demonstrate a cascading dropdown list (populating a child dropdown based on selection of parent dropdown) .
Reader Level:
Download Files:
 


This article is continuation of my previous article on Populating Dropdown list in ASP.NET MVC 2 using Entity Framework 4 @ http://www.c-sharpcorner.com/UploadFile/2124ae/5628/ 

Here I will demonstrate Cascading dropdown list (populating a child dropdown based on selection of a parent dropdown) .

We will be using ajax method in Jquery by using JSON.

Over the course of this article - We will also see how to update Models using the Update Model Wizard in Entity Framework 4.0

I would be referring to database, Models, Views and Controllers used in my previous article @ (http://www.c-sharpcorner.com/UploadFile/2124ae/5628/)
and even the code discussed below would be an addition to the existing sample of the previous article.

1. Update ViewModel

Open IndexViewModel.cs and add code for second dropdown- Cities Drop down list which would serve as child dropdown for the State dropdown (parent dropdown).

//2nd  DropDownList ID
public string ddlCityId
       {
          get;
          set;
       }

//2nd DropDownList Values
public List<SelectListItem> CityValue
       {
          get;
          set;
       }


2. Database part

  • Here we will be creating a new table for cities.
  • Create a new table -> tblCity (CityId(int - primary key, CityName - varchar(30),StateName-varchar(30)) in the existing database - SampleDB.mdf
  • Insert sample cities for each corresponding state values(from tblState) in tblCity.

3. Models

Update Model
  1. We can use Update Model wizard to update the SampleDBModel.edmx file.
    Update Model Wizard serves for the following purpose:

    • ADD -> if an object has not been included in the existing model or if an object has been newly added to database - We can add the object to the Model.
    • REFRESH -> if any of objects definition has been changes in the database -> We can update the object definition in the Model.
    • DELETE -> in case any object (table, stored procedure, Views) has been deleted from database, it removes the object from the Model
     
  2. Here we will use the Update Model wizard to Add -> to basically include tblCity in our Model.
  3. Open SampleDBModel.edmx file.
  4. Right Click the Model browser window and select Update Model from database.

    CascedingDDL1.gif
     
  5. Add tblCity and click Finish -> With this our model is updated with the new table.

    CascedingDDL2.gif

Update Repository Class
  1. Open DataRepository.cs from Models folder
     
  2. Include Code for fetching Cities based on Selected State Name

    //Get the values for City DropDownlist based on Selected State Names
    public List<SelectListItem> GetCityNames(string state_Selected)
           {
                  var vCityName = (from tblCity in entities.tblCities
                  where tblCity.StateName==state_Selected
                  select new SelectListItem
                   {
                         Text=tblCity.CityName,
                         Value=tblCity.CityName
                   }
                                      );
    return vCityName.ToList();
           }

4. Controllers
  • Open HomeController.cs file from Controllers folder
  • Inside ActionResult Index() get the first item in the state dropdown

    //Get the first item of the First drop down list(State ddl)
    string ddlStateId_First_Item = objIndexViewModel.StateValue[0].Value;
     
  • Inside ActionResult Index() - for populating the Cities ddl - on the page load - based on first item in the state ddl

    //Get the City names based on the first Item in the State ddl
    objIndexViewModel.CityValue = objRepository.GetCityNames(ddlStateId_First_Item);
     
  • Write a Controller action that returns a JSONRESULT - to return a list of cities based on selected Sate.

    public JsonResult Cities_SelectedState(string Sel_StateName)
       {
           JsonResult result = new JsonResult();
           var vCities = objRepository.GetCityNames(Sel_StateName);
           result.Data = vCities.ToList();
           result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
           return result;
       }

5. Views
  • Open Index.aspx from Views -> Home -> Views folder.
  • update it with the new Cities label and Cities dropdown

      
    <%:Html.Label("Cities:") %>
      <%:Html.DropDownListFor(m=>m.ddlCityId,Model.CityValue)
    %>

     
  • Include JQuery to populate Cities ddl based on State ddl change.

               <script type="text/javascript">
              $(document).ready(function () {
                  $("#ddlStateId").change(function () {

                      var url = '<%= Url.Content("~/") %>' + "Home/Cities_SelectedState";
                      var ddlsource = "#ddlStateId";
                      var ddltarget = "#ddlCityId";
                      $.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
                          $(ddltarget).empty();
                          $.each(data, function (index, optionData) {
                              $(ddltarget).append("<option value='" + optionData.Text + "'>" + optionData.Value + "</option>");
                          });
     
                      });
                  });
              });
           </script
    >

     

  • Open Site.Master (master page) from Views ->Shared folder and include jQuery script files inside Head Section.

     
    <head runat="server">
     <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
     </head>

6. Compile And Run the Project (F5) - We can see on Page Load City Dropdown got populated based on first item in the State dropdown.

CascedingDDL3.gif

If we Change the value in the State dropdown -> Cities dropdown gets correspondingly populated.

CascedingDDL4.gif

So in this article we have seen how can we implement Cascading DropDownList in ASP.Net MVC using AJAX methos in Jquery by using JSON.

I have attached the code for this sample application.

Happy Learning!!

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 

Kumar; Nice work, and easy to understand and implement. Could you extend it to 4 cascading dropdown lists with MVC2(or MVC3 preferrably) using JQuery. That is: State City Street Name House Number. It will be a wonderful program. I look forward to your reaction to this. ChrisWan condatasystems@live.com

Posted by chris Jun 04, 2011

Kumar; Nice work, and easy to understand and implement. Could you extend it to 4 cascading dropdown lists with MVC2(or MVC3 preferrably) using JQuery. That is: State City Street Name House Number. It will be a wonderful program. I look forward to your reaction to this. Chris Wan

Posted by chris Jun 04, 2011

Hi Kumar, Thank you in advance for your great work. I am trying ti implement the cascading ddl on my project but I´m facing a problem. Lets say i want to store the StateID(GUID) instead of the State name(which is a string). When i try to select the SelectListItems select new SelectListItem { Text = State .Name, Value = State .Id.ToString(), } I get the error " not supported exception was unhandled by user code - LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression." Is there a solution to figure this problem?

Posted by Vicky May 24, 2011

$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) { $(ddltarget).empty(); $.each(data, function (index, optionData) { $(ddltarget).append("<option value='" + optionData.Text + "'>" + optionData.Value + "</option>"); }); In this part in the jquery function you have conceptually error, you put <option value='" + optionData.Text + "'> instead <option value='" + optionData.Value + "'> and the next part is the same. In your program works, because both data are the same. Despite this little error your post help me a lot. Thanks for share it with the world!.

Posted by Nicolas Mijoch May 03, 2011

thank you so much, I have send the email. brgds and thank you.

Posted by sebastian herrera Apr 22, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor