Introduction:

In this article we will learn how to bind DropDownList in mvc or how to bind DropDownList using jqury ajax in mvc  or how to bind DropDownList on selection chage In jquery in mvc with example.

Description:

Here we'll create this scenario in the ASP.NET Web Application based on the MVC 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.

Let’s see simple example of DropDownList

Working With Controller

In the following below code 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 1: Add method named Index() in the Home controller with the following code:

     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();
        }

Now following below code  method named States()  you 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 2: Add method named States() in the Home controller with the following code: 

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

Working With View

Step 1: At first we've add the View for the Index() as defined in the HomeController.cs.

So, right-click on the index method and add view.

 Step 2: Next goto index view and write following below code.

@{
    ViewBag.Title = "index";
}
 
<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script>
    $(document).ready(function () {
        $("#State").prop("disabled", true);
        $("#Country").change(function () {
            if ($("#Country").val() != "Select") {
                var CountryOptions = {};
                CountryOptions.url = "/Home/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))
{
    <div class="col-md-offset-2 col-md-4">
        <h4> Select Country & States </h4> <hr />
        <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>
        <div class="form-group">
            @Html.Label("Select States:", new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                <select id="State" class="form-control"> </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>
    </div>
}
 

Press Ctrl+F5 or F5 to run the application.

 Bind DropDownList in MVC Using jQuery

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

Bind DropDownList in MVC Using jQuery

Thanks for reading and let me know if you have any problem.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like