【发布时间】:2016-10-05 09:01:22
【问题描述】:
我在名为 State 和 City 的视图中有两个下拉菜单。选择 State 时需要显示相应的 Cities 但无法为 City DropDown 提取 CityId 和 CityName。
控制器
public JsonResult cities(int state, Employee employee)
{
var cities = new SelectList(db.Cities.Where(c => c.StateId == state), "CityId", "CityName", employee.City);
return Json(cities,JsonRequestBehavior.AllowGet);
}
jQuery
<script>
$(document).ready(function () {
$("#City").prop("disabled", true);
$("#State").change(function () {
if ($("#State").val() != 1) {
var StateOptions = {};
StateOptions.url = "/Employees/cities";
StateOptions.type = "POST";
StateOptions.data = JSON.stringify({ State: $("#State").val() });
StateOptions.datatype = "json";
StateOptions.contentType = "application/json";
StateOptions.success = function (CitysList) {
$("#City").empty();
for (var i = 0; i < CitysList.length; i++) {
// Unable to extract CityID and CityName in option here
$("#City").append("<option value=" + CitysList[i] + ">" + CitysList[i] + "</option>");
}
$("#City").prop("disabled", false);
};
StateOptions.error = function () { alert("Error in Getting Citys!!"); };
$.ajax(StateOptions);
}
else {
$("#City").empty();
$("#City").prop("disabled", true);
}
});
});
</script>
这些是视图中的州和城市下拉菜单.........
<div class="form-group">
@Html.LabelFor(model => model.State, "State", htmlAttributes: new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.DropDownList("State", null, htmlAttributes: new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, "City", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("City", new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"), "Select City", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
【问题讨论】:
-
获取对象作为响应。但无法提取 cityid 和城市名称。
-
CitysList[i].Value和CitysList[i].Text但您不应该返回SelectList只需返回仅包含您需要的 2 个属性的匿名对象集合。 -var cities = db.Cities.Where(c => c.StateId == state).Select(c => new { Value = c.CityId.ToString(), Text = c.CityName }); -
只需使用
.data = { State: $("#State").val() }; and removeStateOptions.contentType = "application/json";` 并从您的方法中删除Employee employee参数
标签: asp.net-mvc drop-down-menu