[英]Limit Total Selections in Listboxfor in MVC4
I'm setting up a front end that uses MVC4. 我正在设置使用MVC4的前端。 There's several Listboxfor boxes but I want to limit the number of each box up to a certain amount.
有几个Listboxfor框,但我想将每个框的数量限制为一定数量。 For instance Listboxfor1 should have a max of 5 selectable items whereas Listboxfor2 should have a max of 7.
例如,Listboxfor1最多应有5个可选项,而Listboxfor2最多应有7个可选项。
I've done several searches around the web and only found a server side fix using webforms and javascript. 我在网络上进行了几次搜索,仅发现使用Webforms和javascript的服务器端修复程序。 While that's all peaches and cream I can't seem to figure out how apply it to MVC.
虽然这些都是桃子和奶油,但我似乎无法弄清楚如何将其应用于MVC。
Below is a snippet of what my listboxfor code looks like 以下是我的代码清单框的摘要
@Html.ListBoxFor(model => model.Games,
new SelectList(Model.Games.Where(m => m.action == action), "GameID", "Title"),
new { id="listbox" + action, @class="lbGames"})
You cant fix this problem using just using Html helpers. 您不能仅使用HTML帮助器来解决此问题。 You can make some workaround using javascript.
您可以使用javascript进行一些变通。 This
@Html.ListBoxFor
will be converted into html and will look like: 该
@Html.ListBoxFor
将被转换为html,如下所示:
<select id="listbox" class="lbGames">
<option value="Action1">Action1</option>
<option value="Action2">Action2</option>
...
</select>
so you can write something like this using jquery: 因此您可以使用jquery编写如下内容:
$("#listbox").change(function() {
var mySelectedOptions = $.find('#listbox option:selected');
if(if(mySelectedOptions).length > 5){
// Your code here, if selected amount exceeds 5
alert('hey bro you selected more than 5 elements!!!');
}
});
Notice, i didn't tested this code. 注意,我没有测试此代码。 This is just a fast example, to help you to find right way.
这只是一个快速的示例,可以帮助您找到正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.