Thumb

How To Create Cascading Dropdownlist In Asp.Net MVC | Using Jquery Ajax


5/29/2017 12:00:00 AM


Step 1 : Create A Database Table

"Country"

"State"


Step 2 : Click On Visual Studio Create A New Project
Step 3 : Connect Your Database (Like As Vedio).

Step 4 : Create A New Class (Like As Vedio).

Step 5 : Write Down The Below Code In Your Controller

public class HomeController : Controller
    {
        MVCTutorialEntities db = new MVCTutorialEntities();
        public ActionResult Index()
        {
            List<Country> CountryList = db.Countries.ToList();
            ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
            return View();
        }

        public JsonResult GetStateList(int CountryId)
        {
            db.Configuration.ProxyCreationEnabled = false;
            List<State> StateList = db.States.Where(x => x.CountryId == CountryId).ToList();
            return Json(StateList, JsonRequestBehavior.AllowGet);

        }
        
    }

Step 6 : Write Down The Below Code In Your View.

@model CascadingDropDownListDemo.Models.CountryStateViewModel

<br /><br />
<div class="container">
    <div class="form-group">
        @if (ViewBag.CountryList != null)
        {
            @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { @class="form-control"})
        }
    </div>
    <div class="form-group">
            @Html.DropDownListFor(model => model.StateId,new SelectList(" "), "--Select State--", new { @class = "form-control" })
    </div>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {
        $("#CountryId").change(function () {
            $.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
                });
            });
        })
    });
</script>

Run Project

About Teacher

Reza Karim

Software Engineer

More about him