@{
ViewBag.Title = "Main";
}
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function GetState() {
var selectedValue = $('#ddlCountry').val();
window.location.href = '/Bind/GetStatesByID/?countryCode=' + selectedValue;
}
</script>
<h2>Main</h2>
@using (Html.BeginForm())
{
@Html.DropDownList("Country", (SelectList)ViewBag.countryList, "--Choose Your Country--", new { id = "ddlCountry",onchange="GetState();" })
@Html.DropDownList("State", (SelectList)ViewBag.stateList, "--Choose Your State--", new { id = "ddlState" })
}
public class BindController : Controller
{
public ActionResult Index()
{
ViewBag.countryList = GetAllCountrys();
ViewBag.stateList = GetAllStates();
return View("Main");
}
public ActionResult GetStatesByID(int? countryCode)
{
ViewBag.stateList = GetAllStatsByID(countryCode);
ViewBag.countryList = new SelectList(GetAllCountrys(), "Value", "Text", countryCode);
return View("Main");
}
private SelectList GetAllStatsByID(int? countryCode)
{
Data.TestEntities entity = new Data.TestEntities();
{
IEnumerable<SelectListItem> selectedStates = entity.States.Where(s => s.CountryID == countryCode).AsEnumerable().Select(m => new SelectListItem()
{
Text = m.StateName
,
Value = m.StateID.ToString()
});
return new SelectList(selectedStates, "Value", "Text", "--Select State--");
}
}
private SelectList GetAllCountrys()
{
Data.TestEntities entity = new Data.TestEntities();
{
IEnumerable<SelectListItem> country = entity.Countries.AsEnumerable().Select(m => new SelectListItem()
{
Text = m.CountryName
,
Value = m.CountryID.ToString()
});
return new SelectList(country, "Value", "Text","--Select Country--");
}
}
private SelectList GetAllStates()
{
Data.TestEntities entity = new Data.TestEntities();
{
IEnumerable<SelectListItem> states = entity.States.AsEnumerable().Select(m => new SelectListItem()
{
Text = m.StateName
,
Value = m.StateID.ToString()
});
return new SelectList(states, "Value", "Text", "--Select States--");
}
}
}