我的视图“州”和“区”上有两个 DropDownList。我使用以下代码填充“状态”DDL。
控制器:-
var districts = (from r in db.Districts
select new { r.DistrictName });
ViewBag.DistrictName = new SelectList(districts, "DistrictName", "DistrictName");
看法:-
@Html.DropDownList("State", ViewBag.StateName as SelectList, "Select a State")
现在,每当一个人选择州时,JSON致电填充了“地区的DDL。
控制器:-
[HttpGet]
public JsonResult DistrictList(string Id)
{
var districts = (from d in db.Districts
where d.State.StateName == Id
select new { d.DistrictName });
return Json(new SelectList(districts, "DistrictName", "DistrictName"), JsonRequestBehavior.AllowGet);
}
看法:-
<select id="District" name="District"></select>
<script type="text/jscript">
$(function () {
$('#State').change(function () {
$.getJSON('/Application/DistrictList/' + $('#State').val(), function (data) {
var items = '<option>Select a District</option>';
$.each(data, function (i, districts) {
items += "<option value='" + districts.Text + "'>" + districts.Text + "</option>";
});
$('#District').html(items);
});
});
});
</script>
它工作正常,但问题是,每当任何验证失败时,'District' DDL 都会丢失其数据。我再次需要在“州”中进行新的选择,然后“区”从 Json resutl 中获取数据。如何处理?