@ html.DropDown ASP MVC和Select2 multiselect

时间:2017-01-13 19:26:45

标签: asp.net-mvc jquery-select2 jquery-select2-4

我在我的视图中添加了@Html.DropDownList,此下拉列表的数据作为ViewModel中的属性传递。如何将Select2 Multiselect插件添加到此下拉列表中。

@Html.DropDownList("ValueId", new SelectList(item.Values, "Id", "Name"), new { @class = "values js-example-basic-multiple", @multiple ="multiple", @id="dropDown"}) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })`

JQuery的:

$('#dropDown').select2();

页面呈现后:

 `<select class="values js-example-basic-multiple" data-val="true" data-val-number="The field ValueId must be a number." data-val-required="The ValueId field is required." id="dropDown" multiple="multiple" name="ValueId"><option value="4">M</option>

8 红色 `

脚本:

`<script src="/Content/jquery-3.1.1.min.js"></script>`

<link href="/Content/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

更新:我发现了错误。我在我的页面添加了一个新的JQuery实例,我忘了我的shared_layout页面已经添加了一个JQuery实例。

1 个答案:

答案 0 :(得分:3)

根据您提供的信息,有两种选择:

  • 未加载或引用jQuery库。
  • jQuery(或select2)在被调用时没有“准备就绪”。

由于select2依赖于jQuery,因此您必须确保引用它,将所需的代码放在文档就绪块中,以确保您的依赖关系在被称为:

<!-- Your Example List here -->
@Html.DropDownList("Foo", new SelectList(ViewBag.List), new { multiple = "true", id = "dropDown"})

<!-- Example references (prior to closing </body> tag) -->
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
     $(function(){
          $('#dropDown').select2();
     });
</script>

你可以see a complete, and fully functional example using ASP.NET here