HTML5 中的 required="" 属性在 .NET WebForms 中如何使用?

11

我正在尝试在我的.NET 4.5 WebForms应用程序中在表单字段上使用新的required属性。

然而,由于页面上只有一个包围所有控件的<form>(WebForms样式),当按下提交按钮时,浏览器不知道要验证哪些字段。

附有具有登录功能和页面搜索的简化页面版本如下。

当我点击搜索按钮时,浏览器告诉我必须先填写用户名和密码字段。当我尝试登录时,它告诉我必须在搜索字段中输入一些文本。因为所有字段都是同一个<form>标记的子级。

还有其他人遇到过这个问题或想出了解决方案吗?我想使用HTML5表单验证属性,没有JavaScript解决方案。

<!DOCTYPE html>

<html>
<head>
    <title>Title</title>
</head>
<body>
  <form method="post" runat="server" id="mainform">


    <%// Search %>
    <asp:Panel runat="server" DefaultButton="searchButton" >

      <asp:TextBox runat="server" ID="searchQuery" ClientIDMode="Static" required="required" />
      <asp:Button runat="server" ID="searchButton" ClientIDMode="Static" Text="Search"/>

    </asp:Panel>


    <%// Login %>
    <asp:Panel runat="server" DefaultButton="signInButton">

      <label for="inputusername">Username</label>
      <asp:TextBox runat="server" ClientIDMode="Static" ID="inputusername" required="required" />

      <label for="inputpassword">Password</label>
      <asp:TextBox runat="server" TextMode="Password" ClientIDMode="Static" ID="inputpassword" required="required" />

      <asp:Button ID="signInButton" runat="server" />

    </asp:Panel>

  </form>
</body>
</html>

</html>

你尝试过将搜索表单放出来吗? - Francois Borgies
抱歉,我不理解那个。 - chilly
你尝试过在表单外搜索吗? - Francois Borgies
无法这样做。表单标记必须包含所有服务器控件... - chilly
5
HTML5的required属性不允许由任何组设置,而ASP.NET(如果没有愚弄)不允许多个带有服务器控件的form标记。您可以改用RequiredFieldValidator并设置关联控件的ValidationGroup属性。 - Mike Guthrie
那么这就做不到了。既然这样,我至少可以停止寻找解决方案 :) 谢谢 Mike。 - chilly
3个回答

5

请尝试这个方法.. 它对我有效..

<asp:TextBox runat="server" 
             ClientIDMode="Static" 
             ID="inputusername"                    
             required />

重复的 ClientIDMode="Static" 是有意为之吗? - Benjamin Ray

0

-3

由于ASP.Net Web Forms编程模型不允许多个HTML标签,因此您无法利用此功能。


请查看第二个答案。 - Shaharyar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接