Populate Cascading Dropdown List in Asp.net MVC4 using Json and Jquery - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial


Populate Cascading Dropdown List in Asp.net MVC4 using Json and Jquery

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 Country, State and City.
Country:
using System.ComponentModel.DataAnnotations;

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

        public virtual ICollection<State> States { get; set; }
    }

State:
using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

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

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

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

        public virtual State State { get; set; }
    }
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.

Share this

Share on FacebookTweet on TwitterPlus on Google+
loading...

28 comments

Based on selection of country drop down control, which method shall i call first to populate state drop down?

on dropdown selection call the "StateList".............

JSON method not calling properly

what this line mean pls give detail explaination ...
private ProjectContext db = new ProjectContext();

what is the meaning of this code any one tell me briefly
private ProjectContext db = new ProjectContext();
ADVANCE THANKS ......

it is dbcontext class. DbContext :Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model. to see how it create and works see e.g. http://articlemirror.blogspot.in/2013/12/create-read-update-and-delete-in-aspnet.html

it is dbcontext class. DbContext :Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model. to see how it create and works see e.g. http://articlemirror.blogspot.in/2013/12/create-read-update-and-delete-in-aspnet.html

it is dbcontext class. DbContext :Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model. to see how it create and works see e.g. http://articlemirror.blogspot.in/2013/12/create-read-update-and-delete-in-aspnet.html

There is no ViewData item of type 'IEnumerable' that has the key 'Country'.

What version of Jquery is being used in it?? "$.getJSON()" method is not working in it. Is it due to different JQuery version?? I am using MVC4

$.getJSON('/Cascading/StateList/' + $('#Country').val()
in above code what is mean by "/Cascading/StateList/'
please tell me

I just try to create same as yours.but its not populate,please look at this
stackoverflow question I made http://stackoverflow.com/questions/27885702/cascading-dropdown-list-in-asp-net-mvc4-using-json-and-jquery-not-populate

I just try to create same as yours.but its not populate data on State and City dropdown list its only working on the country dropdown

What is the error? You can download the project.

Meaning of ProjectContext db = new ProjectContext(); code to you have create a object of your data context,that means in you db object your all database table would be accessible ,you can query on this table using linq and other

like if you have a table name USER in your database then you can access it by using the linq

var userdata=from usr in db.USER where(usr.id==id)

Now in userdata your desired data would be available.

Specifies which method in which controller the execution will transfer to.
I had to change this to '/Home/StateList/' for it to work properly since my StateList function was in the HomeController

Worked wonderfully!
Thanks!

@Scripts.Render("~bundles/jquery"). how to solve this error??

You are welcome...keep visiting for more articles

I used this on my proyect It's work good but doesn't save the data that I select from the view to model and database.. Could you help me. thanks
Because to save Country i did this
@Html.DropDownListFor(model => model.CountryId, ViewBag.CountryId as SelectList, "Select a Country")
Then.. I tried to do the same with state and city but doesn't save ... and doesnt work the script

where from project contents come........

Thankuu .. ! This is what i was looking for many days

can you please upload a Mini project in MVC its very helpful for us please,, vinishkumar92@gmail.com


EmoticonEmoticon