我在一个可以多选的列表框中有一个包含 40 个结果的列表,但我想将选择的数量限制为某个特定数量,比如说 5。在 C# MVC 中,我有:
@Html.ListBoxFor(model => model.Location, new SelectList(Model.AllLocations, Model.Location), new { id = "AllLocations" })
在控件上设置此约束的最佳方法是什么?
最佳答案
Javascript。 Html 没有为此提供任何机制。像这样:
$(document).ready(function() {
// Add a click event for options in the list.
$('#MyModel_Location option').click(function() {
// Check if the parent has reached the limit of selected items.
if ($(this).parent().val().length > 5) {
// Removed the selected attribute from this option.
$(this).removeAttr("selected");
}
});
});
关于c# - 设置可以在 ListBoxFor<> 中选择的最大项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005108/