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
(Click to Enlarge)
Description:
In the previous article I have explained Populate Dropdown List dynamically using Asp.net MVC Razor, Code First migration in asp.net MVC 4, Create, Read, Update and Delete in Asp.net with MVC 4 Razor view Engine using Entity framework with Code first approach and What is Asp.net MVC? Its advantages and disadvantges.
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.
(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>
Press esc key to do any action using jquery
ReplyDeleteESC Key to do action using JQuery
Based on selection of country drop down control, which method shall i call first to populate state drop down?
ReplyDeleteon dropdown selection call the "StateList".............
Deletewhat is the meaning of this code any one tell me briefly
Deleteprivate 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
DeleteJSON method not calling properly
ReplyDeleteJSON method not calling
ReplyDeletewhat this line mean pls give detail explaination ...
ReplyDeleteprivate ProjectContext db = new ProjectContext();
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
Deleteit 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
DeleteThere is no ViewData item of type 'IEnumerable' that has the key 'Country'.
ReplyDeleteWhat 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$.getJSON('/Cascading/StateList/' + $('#Country').val()
ReplyDeletein above code what is mean by "/Cascading/StateList/'
please tell me
Specifies which method in which controller the execution will transfer to.
DeleteI had to change this to '/Home/StateList/' for it to work properly since my StateList function was in the HomeController
I just try to create same as yours.but its not populate,please look at this
ReplyDeletestackoverflow 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
ReplyDeleteWhat is the error? You can download the project.
Delete@Scripts.Render("~bundles/jquery"). how to solve this error??
DeleteWorked wonderfully!
ReplyDeleteThanks!
You are welcome...keep visiting for more articles
DeleteI 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
ReplyDeleteBecause 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........
ReplyDeleteThankuu .. ! This is what i was looking for many days
ReplyDeleteGlad you hear it helps you.
Deletemy problem
ReplyDeletecan you please upload a Mini project in MVC its very helpful for us please,, vinishkumar92@gmail.com
ReplyDelete