Working With DropDownList in MVC 5 Using jQuery

Introduction

Today we'll learn to work with the DropDownList in the MVC 5 using jQuery. Suppose you need to display the states stored in the DropDownList that are dependent upon on the selected value in another DropDownList named Country.

In that context, here we'll create this scenario in the ASP.NET Web Application based on the MVC 5 Project Template using jQuery. In this article you will learn to create the MVC application and work with the controller and view in it. We'll also use the Razor syntax in the MVC Views.

So, let's start with the following sections:

  • Creating MVC application
  • Working with a Controller
  • Working with a View
  • Running the application

Creating MVC Application

In this section we'll create the ASP.NET MVC application using the following procedure.

Step 1: Open Visual Studio and click on "New Project" and enter the application name as "MvcUsers".

Create Web Application in VS 2013

Step 2: Select the MVC Project Template.

MVC Project Template in VS 2013

That's it for the MVC application creation. Visual Studio automatically creates the MVC 5 application and adds files and folders to it.

Note: I am using Visual Studio 2013 to develop the MVC 5 application. You can create this using MVC 4 also.

Working With Controller

Now we'll add the new scaffolded MVC empty controller here using the following procedure.

Step 1: Just right-click on the Controllers folder and add a New Scaffolded item.

Step 2: Select MVC Controller- Empty.

Controller Scaffolding in MVC 5

Step 3: Enter the controller name as SampleController and modify the Index() with the code below:

  1. public ActionResult Index() {  
  2.     List < string > ListItems = new List < string > ();  
  3.     ListItems.Add("Select");  
  4.     ListItems.Add("India");  
  5.     ListItems.Add("Australia");  
  6.     ListItems.Add("America");  
  7.     ListItems.Add("South Africa");  
  8.     SelectList Countries = new SelectList(ListItems);  
  9.     ViewData["Countries"] = Countries;  
  10.     return View();  
  11. }  

In the code above you can see that the ListItems is a generic string that holds the country names. The DropDownList Html helper in MVC View displays its data in the form of a SelectList object. The object of SelectList is passed to the view using the Countries ViewData variable.

Step 4: Add another method named States() in the same controller with the following code:

  1. public JsonResult States(string Country) {  
  2.     List < string > StatesList = new List < string > ();  
  3.     switch (Country) {  
  4.         case "India":  
  5.             StatesList.Add("New Delhi");  
  6.             StatesList.Add("Mumbai");  
  7.             StatesList.Add("Kolkata");  
  8.             StatesList.Add("Chennai");  
  9.             break;  
  10.         case "Australia":  
  11.             StatesList.Add("Canberra");  
  12.             StatesList.Add("Melbourne");  
  13.             StatesList.Add("Perth");  
  14.             StatesList.Add("Sydney");  
  15.             break;  
  16.         case "America":  
  17.             StatesList.Add("California");  
  18.             StatesList.Add("Florida");  
  19.             StatesList.Add("New York");  
  20.             StatesList.Add("Washignton");  
  21.             break;  
  22.         case "South Africa":  
  23.             StatesList.Add("Cape Town");  
  24.             StatesList.Add("Centurion");  
  25.             StatesList.Add("Durban");  
  26.             StatesList.Add("Jahannesburg");  
  27.             break;  
  28.     }  
  29.     return Json(StatesList);  
  30. }  

In the preceding States() you can see that this accepts the country name and returns the StatesList as JsonResult. This method returns the JsonResult because this will be called using the jQuery. This method returns the states that are based on the country value. Finally, the states generic list is returned to the caller using the Json() method.

Working With View

We've completed the work with the controller, now its time to work with the View. Follow the procedure described below.

Step 1: At first we've add the View for the Index() as defined in the SampleController.cs. So, right-click on the Sample folder to add a View.

Adding View in MVC

Step 2: Enter the View name as Index.

Creating View in Mvc

Step 3: Replace the code with the code below:

  1. @ {  
  2.     ViewBag.Title = "Index";  
  3. } < h2 > Index < /h2> < script src = "~/Scripts/jquery-1.10.2.js" > < /script> < script > $(document).ready(function() {  
  4.     $("#State").prop("disabled"true);  
  5.     $("#Country").change(function() {  
  6.         if ($("#Country").val() != "Select") {  
  7.             var CountryOptions = {};  
  8.             CountryOptions.url = "/Sample/states";  
  9.             CountryOptions.type = "POST";  
  10.             CountryOptions.data = JSON.stringify({  
  11.                 Country: $("#Country").val()  
  12.             });  
  13.             CountryOptions.datatype = "json";  
  14.             CountryOptions.contentType = "application/json";  
  15.             CountryOptions.success = function(StatesList) {  
  16.                 $("#State").empty();  
  17.                 for (var i = 0; i < StatesList.length; i++) {  
  18.                     $("#State").append("<option>" + StatesList[i] + "</option>");  
  19.                 }  
  20.                 $("#State").prop("disabled"false);  
  21.             };  
  22.             CountryOptions.error = function() {  
  23.                 alert("Error in Getting States!!");  
  24.             };  
  25.             $.ajax(CountryOptions);  
  26.         } else {  
  27.             $("#State").empty();  
  28.             $("#State").prop("disabled"true);  
  29.         }  
  30.     });  
  31. }); < /script>  
  32. @using(Html.BeginForm("Index""Sample", FormMethod.Post)) {  
  33.     @Html.AntiForgeryToken() < h4 > Select Country & States < /h4> < hr / > @Html.ValidationSummary() < div class = "form-group" > @Html.Label("Select Country:"new {  
  34.         @class = "col-md-2 control-label"  
  35.     }) < div class = "col-md-10" > @Html.DropDownList("Country", ViewData["Countries"] as SelectList, new {  
  36.         @class = "form-control"  
  37.     }) < /div> < /div><br / > < div class = "form-group" > @Html.Label("Select States:"new {  
  38.         @class = "col-md-2 control-label"  
  39.     }) < div class = "col-md-10" > < select id = "State" > < /select> < /div> < /div> < div class = "form-group" > < div class = "col-md-offset-2 col-md-10" > < input type = "submit"  
  40.     class = "btn btn-default"  
  41.     value = "Submit" / > < /div> < /div>  
  42. }  

In the code above, I used the Razor syntax to show the content in the View. It includes the DropDownList named Country that is rendered by the DropDownList Html helper. The first parameter of this helper represents the name of the DropDownList, the second is the SelectList object that contains the DropDownList values which ID is State.

The jQuery reference is added here manually and inside the script tag the ready() handler the first code will disable the DropDownList using the prop(). The change() handler function at first checks whether the value is selected in the Country and if it is other than "Please Select", the code creates an CountryOptions object. The CountryOptions object holds various settings for the Ajax request to be made to the server for retrieving the State values. There are various properties defined here such as URL that points to the States() method, the type is set to post that indicates that a post method is used whereas the request and data contains the JSON representation of the Country.

Running the Application

In this section we'll run the application and view the Sample Index view using the following procedure.

Step 1: At first open the Views\Shared\_Layout.cshtml and modify the code with the highlighted code below:

  1. <li>@Html.ActionLink("Home""Index""Home")</li>  
  2. <li>@Html.ActionLink("About""About""Home")</li>  
  3. <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  4. <li>@Html.ActionLink("Sample""Index""Sample")</li>  

In the code above, we've added the Sample link for the SampleController in the Home Page of the application.

Step 2: Press Ctrl+F5 or F5 to run the application.

Accessing Controller in MVC

Step 3: You can see the Index page containing the DropDownList

Index View in MVc

Step 4: Now select the country and then the states from the next DropDownList as shown below:

Working with Dropdownlist in MVC

After clicking on "Submit" the default values will display.

Summary

This article described how to work with a Cascading DropDownList in an ASP.NET MVC Application. You can also learn to work with the controller and the corresponding view. Thanks for reading and let me know if you have any problem.


Similar Articles