Hi I am newer in mvc . I want to bind drop down list using model data .
1)Country Dropdown
2)State Dropdown
3)City Dropdown
first time data in country list filled, and in state and city drop down list data set to empty. but on change event of country , state data are not binding. I have send the code which tried. Please give solution.
What I have tried:
Model-----
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Email{ get; set; }
public int CountryId { get; set; }
public int StateId{ get; set; }
public int CityId { get; set; }
public SelectList CountryList { get; set; }
public SelectList CityList { get; set; }
public SelectList StateList { get; set; }
}
------------View ------------------------
@model MyProject.models.MyClass
@Html.DropDownListFor(model =>
model.CountryId,
new SelectList(Model.CountryList, "Value", "Text"),
new
{
@id = "ddlCountry",
@placeholder = "...",
@Class = "chzn-select",
onchange="FillRegion();"
})
@Html.DropDownListFor(model =>
model.StateId,
new SelectList(Model.CountryList, "Value", "Text"),
new
{
@id = "ddlCountry",
@placeholder = "...",
@Class = "chzn-select", onchange="FillRegion();"
})
@Html.DropDownListFor(model =>
model.CityId,
new SelectList(Model.CountryList, "Value", "Text"),
new
{
@id = "ddlCountry",
@placeholder = "...",
@Class = "chzn-select",
onchange="FillRegion();"
})
Controller COde-------------
public ActionResult AddCompanyBranch()
{
MyClass model= new MyClass();
SelectListItem selListItem = new SelectListItem() { Value = "0", Text = "--Select--" };
List<selectlistitem> newList = new List<selectlistitem>();
newList.Add(selListItem);
model.CountryList = listCountry;
model.StateList = new SelectList(newList, "Value", "Text", "0");
model.CityList = new SelectList(newList, "Value", "Text", "0");
return View(model);
}
[HttpPost]
public JsonResult ddCountry_SelectedIndexChanged(string CountryId)
{
return Json(bindState( CountryId));
}
[HttpPost]
public JsonResult ddlState_SelectedIndexChanged(string stateId)
{
JsonResult result = null;
if (stateId != "0")
result = Json(bindCity(stateId));
return result;
}
function FillState() {
var Region = $('#ddlCountry').val();
$.ajax({
type: "POST",
url: '@Url.Action("ddlCountry_SelectedIndexChanged", "Company")',
data: { CountryId: Id},
success: function (data) {
$("#ddlState").empty();
var items = [];
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#ddlState").html(items.join(' '));
}
});
}
function FillCity() {
var stateId = $('#ddlState').val();
$.ajax({
type: "POST",
url: '@Url.Action("ddlState_SelectedIndexChanged", "Company")',
data: { stateId: stateId},
success: function (data) {
$("#ddlCity").empty();
var items = [];
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#ddlCity").html(items.join(' '));
}
});
}