Mvc4 Cascading DropddownList using JQuery and ajax
Introduction :Here in this tutorial explain how to bind data from the database like city, state and country using the entity framework in mvc4 web application. here we can use the Jquery to fetch the data from the controller and and bind these data in to dropdownlist.
After selecting these country,state and city these selected dropdownlist data can be insert in to the registration table in the database using jquery.
Tools: Visual Studio 2012 and Sql server 2008
Step 1: First Create the database and add the table City,State and Country and give relationship
City Table:
State Table :
Country Table :
Step2: After Creating City,State,Country Table add The ADO.NET Entity Modal
Step3 : Add the controller Employee and following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
public ActionResult Index()
{
Database1Entities db = new Database1Entities();
// here country value are pass to view using the viewbag
ViewBag.Country = new SelectList(db.Countries, "CountryID", "CountryName");
return View();
}
public JsonResult GetState(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
var stateList = this.Getstatevalue(Convert.ToInt32(id));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.StateID.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
public IList<State> Getstatevalue(int CountryId)
{
Database1Entities db = new Database1Entities();
return db.States.Where(m => m.CountryID == CountryId).ToList();
}
public JsonResult GetCity(string id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var cityList = this.Getcityvalue(Convert.ToInt32(id));
var cityData = cityList.Select(m => new SelectListItem()
{
Text = m.CityName,
Value = m.CityID.ToString(),
});
return Json(cityData, JsonRequestBehavior.AllowGet);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
public ActionResult Index()
{
Database1Entities db = new Database1Entities();
// here country value are pass to view using the viewbag
ViewBag.Country = new SelectList(db.Countries, "CountryID", "CountryName");
return View();
}
public JsonResult GetState(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
var stateList = this.Getstatevalue(Convert.ToInt32(id));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.StateID.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
public IList<State> Getstatevalue(int CountryId)
{
Database1Entities db = new Database1Entities();
return db.States.Where(m => m.CountryID == CountryId).ToList();
}
public JsonResult GetCity(string id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var cityList = this.Getcityvalue(Convert.ToInt32(id));
var cityData = cityList.Select(m => new SelectListItem()
{
Text = m.CityName,
Value = m.CityID.ToString(),
});
return Json(cityData, JsonRequestBehavior.AllowGet);
}
}
Step 4 : Now you add the View. Here Controller Can be Call using the jquery and ajax as below code.
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeData</legend>
<div class="editor-label">
@Html.Label("Country")<br />
</div>
<div>
@Html.DropDownList("Country", ViewBag.Country as SelectList, "-- Please Select a Country --", new { style = "width:150px",@id="Country" })
</div>
<div class="editor-label">
<br />
@Html.Label("State")<br />
</div>
<div>
@Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "-- Please select a State --",
new { style = "width:150px", @class = "dropdown1" })
</div>
<div class="editor-label">
<br />
@Html.Label("City")<br />
</div>
<div>
@Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), "-- Please select a city --",
new { style = "width:150px", @class = "dropdown2",@id="City" })
</div>
<p>
<input type="button" onclick="ddlInsert()" value="Submit" />
</p>
</fieldset>
}
Now add the Jquery To select City,State,Country and call action method from the controller using ajax
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// this is Country Dropdown Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("Getstates")', // here we are Calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// Get Selected Country ID.
success: function (states) {
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert(' states retrieving fail.' + ex);
}
});
return false;
})
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetCities")', // here we are Calling json method
dataType: 'json',
data: { id: $("#State").val() },
// Get Selected Country ID.
success: function (cities) {
$.each(cities, function (i, city) {
$("#City").append('<option value="' + city.Value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert(' city retrieving fail.' + ex);
}
});
return false;
})
});
</script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// this is Country Dropdown Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("Getstates")', // here we are Calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// Get Selected Country ID.
success: function (states) {
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert(' states retrieving fail.' + ex);
}
});
return false;
})
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetCities")', // here we are Calling json method
dataType: 'json',
data: { id: $("#State").val() },
// Get Selected Country ID.
success: function (cities) {
$.each(cities, function (i, city) {
$("#City").append('<option value="' + city.Value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert(' city retrieving fail.' + ex);
}
});
return false;
})
});
</script>
Screen Shot :
Now We create another table and give name tbl_reg here we can insert above selected dropdownlist value of city,state,country
tbl_reg :
Now add the code in insert code in controller controller as following.
first create the modal and give the data structure in modal class EmployeeData.CS
public class EmployeeData
{
public string Country{ get; set; }
public string State { get; set; }
public string City { get; set; }
}
{
public string Country{ get; set; }
public string State { get; set; }
public string City { get; set; }
}
Add the Controller ActionMethod to Insert Data
public SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.);
public void Insert_data(EmployeeData da)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into tbl_reg values('" + da.Country + "',
'" + da.State + "','" + da.City + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
Now add the Jquery Code And call controller Insert()
<script type="text/javascript">
function ddlInsert() {
var ctr = document.getElementById('Country');
var Country = ctr.options[ctr.selectedIndex].text;
var stt = document.getElementById('State');
var State = stt.options[stt.selectedIndex].text;
var ct = document.getElementById('City');
var City = ct.options[ct.selectedIndex].text;
$.ajax({
url: '@Url.Action("Insert", "Employee")',
data: { Country: Country, State: State, City:City},
type: 'POST',
dataType: 'json',
success: function (data) {
}
});
}
</script>
Now when you select dropdownlist data and click on submit button it can add as following.
Screen Shot :
Hi friend If you have Query or any other problem reguarding the above code or need to project code then contact or give comment in comment box.
See Other Tutorial :
* AngularJS Crude With ASP.NET MVC
* Convert Rows to columns using 'Pivot' in SQL Server
* Mvc Registration page With user exist using Ajax method
* MVC 4 How to Perform Insert Update Delete Edit Select Operation
* MVC4 Edit,update,Delete,cancel inside gridview using sql database
* MVC 4 Gridview To Display Data Using SQL Server Database With Simple code
* Login page in asp.net Mvc4 Web application
* Mvc4 How to bind Dropdown List using Sql Database
* Gridview find control in asp.net
Sign up here with your email
4 comments
Write commentshttp://jsfiddle.net/4ALFU/81/
ReplyI got to know abt this code on comment section od codeproject..Its really helpful
Replythank you swain
ReplyI copied this code as it is as Iam trying to create Registration form but i have an error on this line in the controller var cityList = this.Getcityvalue(Convert.ToInt32(id));. The application does not pick up this.Getcityvalue please help
ReplyConversionConversion EmoticonEmoticon