Html 如何在 mvc 4 中使用多选?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13776851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use multiple select in mvc 4?
提问by Jeyhun Rahimov
I want to use multiple select in Chosen. I have Skill model like,
public class Skill
{
public int Id { get; set; }
public string Name { get; set; }
}
This works in my application:
这适用于我的应用程序:
<select data-placeholder="Choose a Country..." class="chzn-select" multiple >
<option value=""></option>
<option value="United States">United States</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
</select>
I want to replace Countries data with my data. In controller i write:
我想用我的数据替换国家数据。在控制器中我写:
var list = MyService.LoadAllSkills();
ViewBag.Skills = new MultiSelectList(list, "Id", "Name");
In view:
鉴于:
@Html.ListBox("Name", ViewBag.Skills as MultiSelectList,
new { @class = "chzn-select" } )
View result of @Html.ListBox()and @Html.DropDownList()is not like <select>
@Html.ListBox()和@Html.DropDownList() 的查看结果不一样<select>
I get so result:
我得到这样的结果:
But, I want to get result as
但是,我想得到结果
How can I change Chosen sample?
如何更改选择的样本?
采纳答案by Darin Dimitrov
The only difference I can see between the hardcoded example (which you stated that is working) and the one you generate with the ListBox helper is the absence of the data-placeholder
attribute. So:
我能看到的硬编码示例(您说这是有效的)与您使用 ListBox 助手生成的示例之间的唯一区别是缺少该data-placeholder
属性。所以:
@Html.ListBox(
"Countries",
ViewBag.Skills as MultiSelectList,
new { @class = "chzn-select", data_placeholder = "Choose a Country..." }
)
This should at least generate the same markup as what you said is working. If it doesn't work then probably you haven't setup the plugin correctly or you have some other javascript errors. Read the documentation of the plugin about how it should be setup.
这至少应该生成与您所说的相同的标记。如果它不起作用,那么可能是您没有正确设置插件,或者您有其他一些 javascript 错误。阅读插件的文档,了解它应该如何设置。
回答by Code_Worm
as other dudes mentioned, it seems your problem cause is not server-side (razor), it's actually client-side (most probably your Jquery plugin initialization).
正如其他人所提到的,看来您的问题原因不是服务器端(剃刀),它实际上是客户端(很可能是您的 Jquery 插件初始化)。
probably when the plugin initialization called the html DOM is not generated yet, put your plugin initialization script at the end of the body or inside $(document).ready()
and don't forget to take a look at the console to see if there is any errors
可能是在调用html DOM的插件初始化还没有生成的时候,把你的插件初始化脚本放在body的最后或者里面$(document).ready()
,不要忘记看console看看有没有错误
happy coding
快乐编码