Asp.Net MVC 5 Cascading DropDownList Using jQuery

asp.net MVC 5 cascading dropdownlist using jQuery

Here we will discuss how we can create an asp.net mvc application. And then we will discuss how we can do Cascading DropDownList Using jQuery in asp.net mvc 5.

Introduction:

SharePoint deveopment training course

Create the MVC application and work with the controller and view in it. We’ll also use the Razor syntax in the MVC Views. Display the states stored in the DropDownList that are dependent upon on the selected value in another DropDownList named Country.

Description:

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.

Steps To Be Followed:

Step 1: Working With Controller:

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

Also read some asp.net mvc articles:

– Asp.Net MVC Life Cycle and Various State Management Techniques in Asp.Net MVC

– Asp.Net MVC Techniques to transfer data from Controller to View

– How to set up session state in our ASP.NET Core and MVC Core Web applications?

– Steps to archive log files using NLog with ASP.NET Core

  1. Just right-click on the Controllers folder and add a New Scaffolded item.
  2. Select MVC Controller- Empty.

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



Code Ref:

public ActionResult Index() {

List < string > ListItems = new List < string > ();

ListItems.Add(“Select”);

ListItems.Add(“India”);

ListItems.Add(“Australia”);

ListItems.Add(“America”);

ListItems.Add(“South Africa”);

SelectList Countries = new SelectList(ListItems);

ViewData[“Countries”] = Countries;

return View();

}

Code Description:

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 3: Add another method named States() in the same controller with the following code:

Code Ref:

public JsonResult States(string Country) {

List < string > StatesList = new List < string > ();

switch (Country) {

case “India”:

StatesList.Add(“New Delhi”);

StatesList.Add(“Mumbai”);

StatesList.Add(“Kolkata”);

StatesList.Add(“Chennai”);

break;

case “Australia”:

StatesList.Add(“Canberra”);

StatesList.Add(“Melbourne”);

StatesList.Add(“Perth”);

StatesList.Add(“Sydney”);

break;

case “America”:

StatesList.Add(“California”);

StatesList.Add(“Florida”);

StatesList.Add(“New York”);

StatesList.Add(“Washignton”);

break;

case “South Africa”:

StatesList.Add(“Cape Town”);

StatesList.Add(“Centurion”);

StatesList.Add(“Durban”);

StatesList.Add(“Jahannesburg”);

break;

}

return Json(StatesList);

}

Code Description:

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.

Step 4: Working With View:

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

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 named Index.cshtml.



Code Ref:

@ {

 ViewBag.Title = “Index”;

} < h2 > Index < /h2> < script src = “~/Scripts/jquery-1.10.2.js” > < /script> < script > $(document).ready(function() {

 $(“#State”).prop(“disabled”, true);

 $(“#Country”).change(function() {

 if ($(“#Country”).val() != “Select”) {

 var CountryOptions = {};

 CountryOptions.url = “/Sample/states”;

 CountryOptions.type = “POST”;

 CountryOptions.data = JSON.stringify({

 Country: $(“#Country”).val()

 });

 CountryOptions.datatype = “json”;

 CountryOptions.contentType = “application/json”;

 CountryOptions.success = function(StatesList) {

 $(“#State”).empty();

 for (var i = 0; i < StatesList.length; i++) {

 $(“#State”).append(“<option>” + StatesList[i] + “</option>”);

 }

 $(“#State”).prop(“disabled”, false);

 };

 CountryOptions.error = function() {

 alert(“Error in Getting States!!”);

 };

 $.ajax(CountryOptions);

 } else {

 $(“#State”).empty();

 $(“#State”).prop(“disabled”, true);

 }

 });

}); < /script>

@using(Html.BeginForm(“Index”, “Sample”, FormMethod.Post)) {

 @Html.AntiForgeryToken() < h4 > Select Country & States < /h4> < hr / > @Html.ValidationSummary() < div class = “form-group” > @Html.Label(“Select Country:”, new {

 @class = “col-md-2 control-label”

 }) < div class = “col-md-10” > @Html.DropDownList(“Country”, ViewData[“Countries”] as SelectList, new {

 @class = “form-control”

 }) < /div> < /div><br / > < div class = “form-group” > @Html.Label(“Select States:”, new {

 @class = “col-md-2 control-label”

 }) < 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”

 class = “btn btn-default”

 value = “Submit” / > < /div> < /div>

}

Code Description:

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.

Step 5:

open the Views\Shared\_Layout.cshtml and modify the code with the highlighted code below:

Code Ref:

<li>@Html.ActionLink(“Home”, “Index”, “Home”)</li>

<li>@Html.ActionLink(“About”, “About”, “Home”)</li>

<li>@Html.ActionLink(“Contact”, “Contact”, “Home”)</li>

<li>@Html.ActionLink(“Sample”, “Index”, “Sample”)</li>

Code Description:

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

OUTPUT:

asp.net MVC 5 cascading dropdownlist using jQuery
asp.net MVC 5 cascading dropdownlist using jQuery

After clicking on “Submit” the default values will display.

Summary:

Here we had discussed about:

  1. Steps to create Asp.Net MVC Application.
  2. Using jQuery perform cascading dropdownlists.
  3. Obtain value of selection of option in dropdown in button click event handling.
Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Satyaprakash Samantaray

MVP Award Winner | Community Author & Contributor | Software Developer | Most Valuable Blogger(MVB)

View all posts by Satyaprakash Samantaray →