我的观点是
<div id="Countryy">
<div class="editor-label">
@Html.LabelFor(model => model.Country, "Country")
</div>
<div class="editor-field">
@Html.DropDownList("Country", String.Empty)
@Html.ValidationMessageFor(model => model.Country)
</div>
</div>
<div id="Statess">
<div class="editor-label">
@Html.LabelFor(model => model.State, "State")
</div>
<div class="editor-field">
@Html.DropDownList("State", String.Empty)
@Html.ValidationMessageFor(model => model.State)
</div>
</div>
<div id="Cityy">
<div class="editor-label">
@Html.LabelFor(model => model.City, "City")
</div>
<div class="editor-field">
@Html.DropDownList("City", String.Empty)
@Html.ValidationMessageFor(model => model.City)
</div>
</div
MY控制器
public ActionResult Edit(int id)
{
Student student = db.Students.Single(s => s.ID == id);
ViewBag.Country = new SelectList(db.Couns, "ID", "CountryName", student.Country);
ViewBag.State = new SelectList(db.States.Where(d => d.CountryID.Equals(student.Country)), "StateID", "StateName", student.State);
ViewBag.City = new SelectList(db.Cities.Where(x => x.StateID.Equals(student.State)), "CityID", "CityName", student.City);
return View(student);
}
块引用
我的问题是我如何级联国家,州和城市下拉列表。当我想编辑数据时生成此视图。从db中保存的数据被重新检索并绑定到控件但是当用户更改国家/地区的值时下拉状态比状态下拉列表也应根据它填充。我在db中有国家,州,城市3个不同的表格,其中包含所需的pk和fk
答案 0 :(得分:1)
以下是使用Ajax的MVC中国家和州级联下拉列表的解决方案: -
通过控制器保留视图包进行第一次下拉绑定,对于第二次下拉,我们可以使用JavaScript / Jquery根据所选国家/地区填充值。
下面是cshtml页面上使用的代码:
<div class="editor-label">
@Html.LabelFor(m => m.Country)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Country, new SelectList(Model.Country, "Value", "Text"), "Select Contry", new { onchange = "CountryChange()" })
</div>
<div class="editor-label">
@Html.LabelFor(m => m.State)
</div>
<div class="editor-field">
@Html.DropDownList("state","Select State")
</div>
我们使用“CountryChange()”javascript函数根据国家/地区更改在状态下拉列表中获取和填充数据。下面是JavaScript函数实现。
<script language="JavaScript" type="text/JavaScript">
function CountryChange () {
var url = '@Url.Content("~/Account/GetState")';
var ddlsource = "#Country";
var ddltarget = "#State";
if ($(ddlsource).val() != "") {
$.ajaxSetup({ cache: false });
$.getJSON(url, { Sel_Country: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$("#State").append("<option value=''>Select State</option>");
$.each(data, function (index, optionData) {
$("#State").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
else {
$("#State").empty();
$("#State").append("<option value=''>Select State</option>");
}
}
</script>
这里json url指定“〜/ Account / GetState”是“帐户”控制器中可用的方法“GetState”,用于检索数据并以json格式传递数据。
public JsonResult GetState (string Sel_Country)
{
CountryService db = new CountryService ();
JsonResult result = new JsonResult();
var vStateList = db.GetStateList(Convert.ToInt64(Sel_Country));
result.Data = vStateList.ToList();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}