我的视图'State'和'District'上有两个DropDownList。我使用以下代码填充'State'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调用就会填充'District'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>
它工作正常,但问题是,无论何时任何验证失败,'区'DDL都会丢失其数据。我再次需要在'State'中进行新选择,然后'District'从Json resutl获取数据。怎么处理这个?
答案 0 :(得分:0)
给你的第一个选项一个虚拟值,然后在后端检查它:
var items = '<option value="-1">Select a District</option>';