Sunday, January 19, 2014

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.

26 comments:

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

    ReplyDelete
    Replies
    1. on dropdown selection call the "StateList".............

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

      Delete
    3. 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

      Delete
  2. JSON method not calling properly

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

    ReplyDelete
    Replies
    1. 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

      Delete
    2. 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

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

    ReplyDelete
  5. 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

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

    ReplyDelete
    Replies
    1. 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

      Delete
  7. 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

    ReplyDelete
  8. 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

    ReplyDelete
    Replies
    1. What is the error? You can download the project.

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

      Delete
  9. Worked wonderfully!
    Thanks!

    ReplyDelete
    Replies
    1. You are welcome...keep visiting for more articles

      Delete
  10. 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

    ReplyDelete
  11. where from project contents come........

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

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

    ReplyDelete