MVC : Cascading DropdownList - ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

MVC : Cascading DropdownList

Introduction: In this article today I am going to explain how we can Populate Cascading Dropdown List in Asp.net MVC4 using Json and Jquery
Populate Cascading Dropdown
(Click to Enlarge)
Description:

I want to populate State dropdown on Country selection and on State Dropdown Selection populate City dropdown. I have three classes in model CountryState and City.
Country:
using System.ComponentModel.DataAnnotations;

public class Country
    {
        [Key]
        public int CountryId { getset; }
        public string CountryName { getset; }

        public virtual ICollection<State> States { getset; }
    }

State:
using System.ComponentModel.DataAnnotations;



using System.ComponentModel.DataAnnotations.Schema;

public class State
    {
        [Key]
        public int StateId { getset; }
        public string StateName { getset; }
        [ForeignKey("Country")]
        public int CountryId { getset; }

        public virtual Country Country { getset; }
        public virtual ICollection<City> Citys { getset; }
    }
City:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class City
    {
        [Key]
        public int CityId { getset; }
        public string CityName { getset; }
        [ForeignKey("State")]
        public int StateId { getset; }

        public virtual State State { getset; }
    }
After that I add a new Empty MVC Controller to project.
Populate Cascading Dropdown
                                                                   (Click to Enlarge)
Write the given code:

using MVCAPPLICATION.Models;

private ProjectContext db = new ProjectContext();
public ActionResult Index()
        {
            ViewBag.CountryId = new SelectList(db.Countrys, "CountryId""CountryName");
            return View();
        }
        public JsonResult StateList(int Id)
        {
            var state = from s in db.States
                           where s.CountryId == Id
                           select s;
            return Json(new SelectList(state.ToArray(), "StateId""StateName"), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Citylist(int id)
        {
            var city = from c in db.Citys
                       where c.StateId == id
                       select c;
            return Json(new SelectList(city.ToArray(), "CityId""CityName"), JsonRequestBehavior.AllowGet);
        }
        public IList<State> Getstate(int CountryId)
        {
            return db.States.Where(m => m.CountryId == CountryId).ToList();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadClassesByCountryId(string CountryName)
        {
            var stateList = this.Getstate(Convert.ToInt32(CountryName));
            var stateData = stateList.Select(m => new SelectListItem()
            {
                Text = m.StateName,
                Value = m.CountryId.ToString(),
            });
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }

Now add a Empty view for Controller.

@model MVCAPPLICATION.Models.ProjectContext

@using (Html.BeginForm())
{
@Html.DropDownList("Country", ViewBag.CountryId as SelectList"Select a Country"new { id="Country" })<br />
    <select id="State" name="state"></select><br />
    <select id="city" name="City"></select><br />
}

Add Jquery to view:

@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(function () {
        $('#Country').change(function () {
            $.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data) {
                var items = '<option>Select a State</option>';
                $.each(data, function (i, state) {
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                });
                $('#State').html(items);
            });
        });
       
        $('#State').change(function () {
            $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) {
                var items = '<option>Select a City</option>';
                $.each(data, function (i, city) {
                    items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                });
                $('#city').html(items);
            });
        });
    });
</script>

Build and run the project.

Download the project:

Is this article helpful for you?

If yes post your comment to appreciate my work and fell free to contact me. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.


EmoticonEmoticon