Home > DeveloperSection > Articles > Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4


ASP.NET MVC ASP.NET MVC 
Ratings:
1 Comment(s)
 15631  View(s)
Rate this:

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

In this article, I’m explaining the how create cascading drop down list using ajax in asp.net mvc 4.

Step 1

First create two tables named “Country” and “State” like this:

Country Table

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

State Table

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Create foreign key “CountryId” between these two tables.

And add some data in both the tables like this:

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Step 2

Now create a basic asp.net mvc 4 application and add a class named “Country” to it:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;

 

namespace CascadingDropdownlistMvcApp.Models

{

    [Table("Country")]

    public class Country

    {

        [Key]

        public int CountryId { getset; }

        public string CountryName { getset; }

    }

}

 

Step 3

Now add a class “State” to the project like this:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;

 

namespace CascadingDropdownlistMvcApp.Models

{

    [Table("State")]

    public class State

    {

        [Key]

        public int Id { getset; }

        public int CountryId { getset; }

        public string StateName { getset; }

    }

}

Step 4

Now add another class named “CountryContext” to the project like this:

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace CascadingDropdownlistMvcApp.Models

{

    public class CountryContext : DbContext

    {

        public DbSet<Country> Countries { getset; }

        public DbSet<State> States { getset; }

 

    }

}

Step 5

Now add a controller named “HomeController” to the project and write the below code in it:

using CascadingDropdownlistMvcApp.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace CascadingDropdownlistMvcApp.Controllers

{

    public class HomeController : Controller

    {

        CountryContext db = new CountryContext();

 

        public ActionResult Index()

        {

            return View();

        }

 

        public JsonResult GetCountries()

        {

            return Json(db.Countries.ToList(), JsonRequestBehavior.AllowGet);

        }

 

        public JsonResult GetStatesByCountryId(string countryId)

        {

            int Id = Convert.ToInt32(countryId);

 

 

            var states = from a in db.States where a.CountryId == Id select a;

 

            return Json(states);

        }

 

    }

}

 

Step 6

Now add a view named “Index” to the project like this:

@{

    ViewBag.Title = "Index";

}

 

<script src="~/Scripts/jquery-1.8.2.min.js"></script>

<script>

    $(function () {

        $.ajax({

            type: "GET",

            url: "/home/getcountries",

            datatype: "Json",

            success: function (data) {

                $.each(data, function (index, value) {

                    $('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.CountryName +'</option>');

                });

            }

        });

 

        $('#dropdownCountry').change(function () {

 

            $('#dropdownState').empty();

 

            $.ajax({

                type: "POST",

                url: "/home/GetStatesByCountryId",

                datatype: "Json",

                data: { countryId: $('#dropdownCountry').val() },

                success: function (data) {

                    $.each(data, function (index, value) {

                        $('#dropdownState').append('<option value="'+ value.Id+'">'+ value.StateName+'</option>');

                    });

                }

            });

        });

    });

</script>

 

<h2>Cascading DropDownList Sample</h2>

 

<div>

    <div>

        @Html.DropDownList("dropdownCountry"new SelectList(string.Empty, "Value""Text"), "Please select a country",new { @style="width:250px;"})

    </div>

    <div style="margin-top:50px;">

        @Html.DropDownList("dropdownState"new SelectList(string.Empty, "Value""Text"), "Please select a state"new{ @style="width:250px;"})

    </div>

</div>

 

Output

Now run the application:

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

 


Thank you

By Taku Fujii on   12 hours ago
Finally, I can fully understand how to use ajax for loading the dropdown lists.  There are so much examples with excessive instruction, while yours is the simplest, thus most elegant and helpful.

Don't want to miss updates? Please click the below button!

Follow MindStick