我有一个CheckBoxList控件,我想要求用户至少选中一个框,不管他们是否选中每一个,或者3个,甚至只是一个.

本着asp的精神.net的验证控件,我可以使用什么来强制执行它?我还使用了Ajax验证扩展程序,所以如果它看起来像其他控件,而不是codebehind中一些俗气的服务器验证方法,那就太好了.

<asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
    <asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
    <asp:ListItem Text="Final Construction" Value="final_construction" />
    <asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
    <asp:ListItem Text="Remodel" Value="remodel" />
    <asp:ListItem Text="Color" Value="color" />
    <asp:ListItem Text="Brick" Value="brick" />
    <asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
    <asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
    <asp:ListItem Text="Fence/Screening" Value="fence_screening" />
    <asp:ListItem Text="Landscape - Front" Value="landscape_front" />
    <asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
    <asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>

推荐答案

在验证服务器端做这件事很容易,但是我假设您想要在客户端做这件事?

JQuery可以很容易地做到这一点,只要你有一些所有复选框控件都有共同之处,可以用作 Select 器,比如类(你的.NET控件上的CssClass).您可以制作一个简单的JQuery函数,并将其连接到ASP.NET自定义验证程序.请记住,如果您确实使用自定义验证程序,以确保在javascript不工作的情况下判断服务器端,那么您不会像另一个一样获得免费的服务器端判断.NET验证器.

有关自定义验证器的更多信息,请查看以下链接:www.asp.net

你不需要使用JQuery,它只会让javascript函数更容易地迭代和查看所有复选框控件,但是如果你喜欢,你可以使用普通的javascript.

下面是我在以下网址找到的一个示例:Link to original

<asp:CheckBoxList ID="chkModuleList"runat="server" >
</asp:CheckBoxList>

<asp:CustomValidator runat="server" ID="cvmodulelist"
  ClientValidationFunction="ValidateModuleList"
  ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>

// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
  var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
  var chkListinputs = chkListModules.getElementsByTagName("input");
  for (var i=0;i<chkListinputs .length;i++)
  {
    if (chkListinputs [i].checked)
    {
      args.IsValid = true;
      return;
    }
  }
  args.IsValid = false;
}

旁注:JQuery只是一个需要添加到页面中的小js文件.一旦你把它包括在内,你就可以使用所有你喜欢的JQuery个.无需安装,我认为下一版本的Visual Studio将完全支持它.

Asp.net相关问答推荐

Windows 命令行中的/p:是什么意思

在 Windows Server 2008 IIS7 上的 ASP.NET 中写入事件日志(log)

逐步 ASP.NET 自动构建/部署

如何正确配置 IHttpModule?

Web 服务器配置为不列出此目录的内容. asp.net vs 2012 错误?

Firefox 和 Chrome 之间 1 像素的行高差

'Access-Control-Allow-Origin' 标头包含多个值 '*, *',但只允许一个

如何为发布模式设置调试错误

如何使用 javascript 获取 MVC 应用程序的基本 URL

如何使用 javascript 调用 ASP.NET c# 方法

如何在 ASP.NET 下拉列表中添加选项组?

如何设置 CSS 切换器

使用 ASPNet_Regiis 加密自定义配置部分 - 你能做到吗?

如何设置默认页面 asp.net

ASP.NET Core 2.0 为同一端点结合了 Cookie 和承载授权

如何在 ASP.Net 的客户端 (JavaScript) 上判断 Page.Validate()?

IIS Express 安装目录在哪里?

ASP.NET Core 中的 NuGet 包位置在哪里?

强制 IIS Express 进入classic 管道模式

获取 Application_Start 中的当前应用程序物理路径