This article shows how to create a Cascading
Dropdownlist.
We are using JSON with razor syntax.
We are using JSON with razor syntax.
For database connectivity we are using ADO.net without Entity Framework
Please note that I am considering that you are
aware of MVC projects that how to open them and how to Add Controller and
Models in the project. So now we proceed -
Step 1:
Create tables of Country and states in SQL Server. Follow the following snap shot:
Table name: country
Table name:
states
Fill some date in Tables. For example-
Step 2:
Create a class in model of name CountryModel. The code is –
public class CountryModel
{
public int? countryId { get; set; }
public string cname { get; set; }
public int? StateId { get; set; }
public string statename { get; set; }
public List<CountryModel> conList { get; set; }
}
Here question mark (?) after data type int is showing to the nullable
type.
Step 3:
Add extra following namespaces to the controller –
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using MVC18042016.Models; // use
your application name in place of ‘MVC18042016’
Now add remaining code of the controller-
public ActionResult Index()
{
List<CountryModel> contry =
GetAllCountry();
ViewBag.country = contry;
return View();
}
public List<CountryModel> GetAllCountry() //
{
List<CountryModel> li = new List<CountryModel>();
DataTable dt = Get GetCont();
foreach (DataRow dr in dt.Rows)
{
CountryModel cl = new CountryModel()
{
countryId = Convert.ToInt32(dr["countryId"]),
cname = dr["cname"].ToString(),
};
li.Add(cl);
}
return li;
}
public DataTable GetCont() //
{
SqlConnection con = new SqlConnection("Data Source= MyPC;Initial
Catalog=DBFirst;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from
country",
con);
DataTable dt = new
DataTable();
da.Fill(dt);
return dt;
}
public DataTable GetStateById(int id) //
{
SqlConnection con = new SqlConnection("Data Source=MyPC;Initial
Catalog=DBFirst;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from
states where Country_id=" + id + "", con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public JsonResult GetCountries()
{
List<CountryModel> contry =
GetAllCountry();
return Json(contry, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryId(string countryId)
{
List<CountryModel> li = new List<CountryModel>();
int
Id = Convert.ToInt32(countryId);
DataTable dt = GetStateById(Id);
foreach (DataRow dr in dt.Rows)
{
CountryModel cl = new CountryModel()
{
countryId = Convert.ToInt32(dr["Country_id"]),
statename = dr["statename"].ToString()
};
li.Add(cl);
}
return Json(li);
}
Details: In the
above code I have put all methods and code in the controller only, but this is
not good approach. I did this for your convenience. Please put the code in your
BLClass and DAL class as per need. Because it’s always a good approach to keep
User defined methods in the BLClass and Data Access codes in the DAL Class.
Here GetAllCountry()
method is used to fetch all countries from database.
GetStateById() method is
used to fetch all states as per country id is passed.
GetCountries() and GetStatesByCountryId() are
two methods which are returning Json Data which will be used in the view.
Step 4:
Add the view to the Index() action with View
name: Index, Template: Create, Model Class: country.
Step 5:
Change the code at the place where you required dropdown list-
For Country Drop Down-
@Html.DropDownList("Country", new SelectList(ViewBag.country, "countryId", "cname"), "-- Select
--")
For States Drop Down
@Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Select a
State", new { style = "width:250px", @class = "dropdown1" })
Step 6:
Add the JQuery code inside<head>---</head> section of the page, if
have (if you are using master page for your view, head section will not present).
Code is-
<script>
$(function () {
$.ajax({
type: "GET",
url: "/DropDown/GetCountries", // path of Json method
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#Country').append('<option value="' + value.countryId + '">' + value.cname + '</option>');
});
}
});
$('#Country').change(function () {
$('#State').empty();
$.ajax({
type: "POST",
url: "/DropDown/GetStatesByCountryId",
datatype: "Json",
data: { countryId: $('#Country').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#State').append('<option value="' + value.StateId + '">' + value.statename + '</option>');
});
}
});
});
});
</script>
Run the application. Use Url : http://localhost:<number>/DropDown/Index
Happy Coding.
By - Rudra Pratap Singh
Software Engineer
Contact me : singhrudrapratap29[at]gmail[dot]com
No comments:
Post a Comment