c# - 设置可以在 ListBoxFor<> 中选择的最大项目数

标签 c# asp.net-mvc-3 razor listbox

我在一个可以多选的列表框中有一个包含 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/

相关文章:

c# - Linq to Entities Group By 那里有一些没有元素的组

c# - 如何在gridview中求和从asp.net数据库中选择数据

c# - 序列化 List<T> 错误反射(reflect)字段

c# - 更新语法不适用于所有列

c# - (Action<T>).Name 不返回预期值

c# - 新 MVC3 项目中的 InversionOfControl

c# - 如果 URL 包含片段,为什么 Url.IsLocalUrl 会返回 false?

asp.net-mvc - 如何避免重复此网格配置代码?

asp.net-mvc-3 - ASP.NET MVC 动态外部 URL

c# - 客户端自定义数据注释验证