【问题标题】:Select items in multiselect dropdown list MVC3 jquery在多选下拉列表MVC3 jquery中选择项目
【发布时间】:2013-10-11 05:20:56
【问题描述】:

如何使用 jquery 在多选下拉列表中设置值。我正在使用 MVC3 Razor 视图来显示多选下拉列表并使用 http://quasipartikel.at/multiselect_next/ 这个多选插件。

 <div class="editor-field">         
   @Html.DropDownListFor(model => model.ActionId, (SelectList)ViewBag.ActionsList, new { @class = "multiselect", @multiple = "multiple", @style = "width: 450px;height:300px" })
    @Html.ValidationMessageFor(model => model.ActionId)   
</div>
<button onclick="setValues()">Set values </button>

在javascript中我使用了代码

function setValues() {      
    var valArr = [2, 3, 5];
    var i = 0, size = valArr.length;
    var  $options = $('#ActionId option');
    for (i; i < size; i++) {           
        // $("#ActionId option[value='" + valArr[i] + "']").attr("selected", 1); this is also not working
        $("#ActionId option[value='" + valArr[i] + "']").attr("selected", true);
    }     
}

但是在按钮的单击事件中没有选择这些值。 当我刷新页面时,值被选中。 我怎样才能克服这个?我想使用 javascript 在按钮单击时设置 multdropdown 列表中的值

【问题讨论】:

    标签: jquery asp.net-mvc-3 razor html-select


    【解决方案1】:

    您应该提供字段名称,其值将由 Razor 引擎绑定到下拉列表,因为您需要在下拉列表中提供要绑定的属性名称。 试试这个

    @Html.DropDownListFor(model => model.ActionId, new SelectList(@ViewBag.ActionsList,"AccountID","AccountName"), new { @class = "multiselect", @multiple = "multiple", @style = "width: 450px;height:300px" })
    

    其中 AccountId,AccountName 是 ActionsList 中的属性字段 和 AccountName 值将显示在页面中,AccountId 将在选择时绑定

    在您的情况下,检查 ActionsList 并将存在的属性名称替换为 AccountId 和 AccountName

    【讨论】:

    • 但是如何设置下拉列表中的选定值?我的下拉菜单是多选的,我想将一些值设置为选中状态。我该怎么做?
    • 这似乎没有正确绑定到所选项目的视图上。将所选值绑定到模型而不是从模型绑定到视图以显示先前选择的内容的另一种方式可以正常工作
    【解决方案2】:

    你可以使用choosen js来做多选功能。

    请参考本文档和演示。

    http://harvesthq.github.io/chosen/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多