【发布时间】:2017-12-08 13:12:37
【问题描述】:
使用 MVC 4,我正在尝试根据另一个下拉列表的操作更改 @Html.DropDownListFor 视图中的显示值。在下面的示例中,当用户选择状态列表中的任何值时,我希望 @Html.DropDownListFor 显示索引的 203 值,即 US。如何做到这一点?
//in the controller
ViewBag.statelist = new SelectList(db.states, "state_abbr", "state_name");
ViewBag.countrylist = new SelectList(db.countries, "country_id", "country_name", -1);
//in the View
<div class="form-group">
@Html.LabelFor(model => model.states)
@Html.DropDownList("ddlstate", ViewBag.statelist as SelectList, Model.rrq_sec1_waddr_stprov, htmlAttributes: new { @onchange="StateChange()" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.country)
@Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { @id="ddlcountry" })
</div>
//javascript
function StateChange() {
var state = document.getElementById("ddlstate").value;
$("#ddlcountry").val = 203;
};
如何让#ddlcountry index=203(即“美国”)出现在视图中,然后状态下拉列表发生变化?
【问题讨论】:
-
你试过
$("#ddlcountry").val(203);而不是$("#ddlcountry").val = 203;吗? -
工作完美 - 谢谢。
标签: javascript asp.net-mvc html.dropdownlistfor