Cascading Dropdownlist using Ajax in Asp.Net Mvc 4
In this
blog, I’m explaining how to create cascading dropdownlist using ajax in asp.net
mvc 4.
Cascading
dropdownlist means there will be two or more than two dropdownlist in a single
webpage and one dropdownlist will be based on other dropdownlist means once we
select value in one dropdownlist, it will filter the value in the second
dropdownlist.
Example
In this
example, we will have three dropdownlist – Country, State, City. Once we select
the value in Country dropdownlist – it will filter the value in State
dropdownlist and once we select the value in the State dropdownlist – it will
filter the value in the City dropdownlist and all these task will going to
achieve using ajax because we don’t want to reload the page each and every time
the user selects the value in any of the dropdownlist.
Step 1
First
create three tables in the database like this:
Country
State
City
Step 2
Now create
a basic asp.net mvc 4 application and add three model class like this:
CountryModel
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 CountryModel
{
[Key]
public int CountryId { get; set; }
public string Country { get; set; }
}
}
StateModel
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 StateModel
{
[Key]
public int Id { get; set; }
public int CountryId { get; set; }
public string State { get; set; }
}
}
CityModel
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("City")]
public class CityModel
{
[Key]
public int Id { get; set; }
public int StateId { get; set; }
public string City { get; set; }
}
}
Step 3
Now add another class to
the project named “CountryEntities” like this:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace CascadingDropDownListMvcApp.Models
{
public class CountryEntities : DbContext
{
public DbSet<CountryModel> Countries { get; set; }
public DbSet<StateModel> States { get; set; }
public DbSet<CityModel> Cities { get; set; }
}
}
Step 4
Now add a controller to
the project named “HomeController” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadingDropDownListMvcApp.Models;
namespace CascadingDropDownListMvcApp.Controllers
{
public class HomeController : Controller
{
CountryEntities db = new CountryEntities();
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);
}
public JsonResult GetCitiesByStateId(string stateId)
{
int Id = Convert.ToInt32(stateId);
var cities = from a in db.Cities where a.StateId == Id select a;
return Json(cities);
}
}
}
Step 5
Now add a view to the
project named “Index” and write the below code in it:
@{
ViewBag.Title =
"Index";
}
<script src="~/Scripts/jquery-1.7.1.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.Country + '</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.State + '</option>');
});
}
});
});
$('#dropdownState').change(function () {
$('#dropdownCity').empty();
$.ajax({
type: "POST",
url: "/home/GetCitiesByStateId",
datatype: "Json",
data: { stateId: $('#dropdownState').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCity').append('<option value="' + value.Id + '">' + value.City + '</option>');
});
}
});
});
});
</script>
<h2>Cascading DropDownList Sample</h2>
<div>
<div style="width: 100%;float:left;">
<div style="width: 100px; float: left;">
<label>Country : </label>
</div>
<div style="width: 200px; float: left;">
@Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please
select country", new { @style = "width:200px;" })
</div>
</div>
<div style="width: 100%;float:left;margin-top:35px;">
<div style="width: 100px; float: left;">
<label>State : </label>
</div>
<div style="width: 200px; float: left;">
@Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please
select state", new { @style = "width:200px;" })
</div>
</div>
<div style="width: 100%;float:left;margin-top:35px;">
<div style="width: 100px; float: left;">
<label>City : </label>
</div>
<div style="width: 200px; float: left;">
@Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please
select city", new { @style = "width:200px;" })
</div>
</div>
</div>
Step 6
Now add the connection
string in the web.config file like this:
<connectionStrings>
<add name="CountryEntities" connectionString="Data Source=DELL-PC\SQLEXPRESS;Initial Catalog=sumit_db;Integrated
Security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Now your solution explorer
looks like this:
Output
Now run the application
Thank you for reading this blog please put
your valuable comment or any suggestion/question in the comment box.
good codding.thanks
ReplyDeleteThank you! Initially it works, but when I go back and choose "Please select country" it breaks because there is no value for this item. How can I solve this so that it resets to the initial state; Please select country, Please select state, please select city?
ReplyDeletehi sumit thanks for good article. Can you post one article for edit the same dropdownlist in mvc
ReplyDeleteThis comment has been removed by the author.
ReplyDeletenic sir !!
ReplyDelete