【问题标题】:MVC @Html.DropDownListFor change displayed value in javascriptMVC @Html.DropDownListFor 更改 javascript 中的显示值
【发布时间】: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


【解决方案1】:

这可能有助于您在第二个下拉列表中选择值,使用此 jQuery 函数在第一个下拉列表的 onchange 事件中选择值。

 $('#ddlstate').change(function () {
 $("#ddlcountry").val( $('#ddlstate').val());
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    相关资源
    最近更新 更多