【问题标题】:Visual Studio Web form not validatingVisual Studio Web 表单未验证
【发布时间】:2013-09-24 02:15:28
【问题描述】:

这是我的 Web 表单。名字是必需的,但是当我运行程序并将 FirstName 字段留空时,我仍然会看到感谢我填写调查表的页面。它应该告诉我名字是必需的。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Cheese.aspx.cs" Inherits="WebApplication1.Cheese" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form2" runat="server">
    <div style="width: 37px">
        <asp:Panel ID="PanelNameForm" runat="server" Width="502px">
            <asp:Label ID="LabelFirstName" runat="server" Text="First Name"></asp:Label>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBoxFirstName"></asp:RequiredFieldValidator>
            <asp:TextBox ID="TextBoxFirstName" runat="server"></asp:TextBox>
            <asp:Label ID="LabelLastName" runat="server" Text="Last Name"></asp:Label>
            <asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox> <br />
            <asp:Label ID="LabelAddr1" runat="server" Text="Address"></asp:Label>
            <asp:TextBox ID="TextBoxAddr1" runat="server"></asp:TextBox>
            <asp:Label ID="LabelAddr2" runat="server" Text="Address"></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <br />
            City<asp:TextBox ID="TextBoxAddr2" runat="server"></asp:TextBox>
            State<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            Zip<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <br />
            Phone Number<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
            email<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
            Age<asp:DropDownList ID="DropDownList2" runat="server">
                <asp:ListItem Value="1">0-17</asp:ListItem>
                <asp:ListItem Value="2">18-21</asp:ListItem>
                <asp:ListItem Value="3">22-25</asp:ListItem>
                <asp:ListItem Value="4">26-35</asp:ListItem>
                <asp:ListItem Value="5">36+</asp:ListItem>
            </asp:DropDownList>
            <asp:Panel ID="Panel1" runat="server" Width="407px">
                Gender<asp:RadioButtonList ID="RadioButtonList1" runat="server">
                    <asp:ListItem Value="Male">Male</asp:ListItem>
                    <asp:ListItem Value="Female">Female</asp:ListItem>
                </asp:RadioButtonList>
                Favorite Cheese<asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                <br />
                How often do you eat cheese? (Check one)<asp:CheckBoxList ID="CheckBoxList1" runat="server">
                    <asp:ListItem>Every Day</asp:ListItem>
                    <asp:ListItem>Every Other Day</asp:ListItem>
                    <asp:ListItem>Once A Week</asp:ListItem>
                    <asp:ListItem>I Don&#39;t Like Cheese</asp:ListItem>
                </asp:CheckBoxList>
                Cheese Texture Preferences (Check All That Apply)<asp:CheckBoxList ID="CheckBoxList2" runat="server">
                    <asp:ListItem Value="1">Hard</asp:ListItem>
                    <asp:ListItem Value="2">Semi-hard</asp:ListItem>
                    <asp:ListItem Value="3">Semi-soft</asp:ListItem>
                    <asp:ListItem Value="4">Soft</asp:ListItem>
                    <asp:ListItem Value="5">Crumbly</asp:ListItem>
                </asp:CheckBoxList>
                Milk Type Preferences (Check All That Apply)<asp:CheckBoxList ID="CheckBoxList3" runat="server">
                    <asp:ListItem>Buffalo</asp:ListItem>
                    <asp:ListItem>Cow</asp:ListItem>
                    <asp:ListItem>Goat</asp:ListItem>
                    <asp:ListItem>Vegetarian</asp:ListItem>
                </asp:CheckBoxList>
                     <asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click" />
                </asp:Panel>
        </asp:Panel>
        <asp:Panel ID="PanelThankYou" runat="server" Width="442px">
            Thank you for taking the survey, <asp:Label ID="LabelThankYouName" runat="server" Text=""></asp:Label>
        </asp:Panel>
    </div>
    </form>
</body>
</html>

这是提交按钮的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Cheese : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(Page.IsPostBack))
            {
                //first time page is loaded
                PanelThankYou.Visible = false;
            }
            else
            {

            }
        }

        protected void Button_Click(object sender, EventArgs e)
        {
            PanelNameForm.Visible = false;
            PanelThankYou.Visible = true;

            LabelThankYouName.Text = TextBoxFirstName.Text + " " + TextBoxLastName.Text + "!";
        }
    }
}

【问题讨论】:

    标签: c# validation webforms


    【解决方案1】:

    如果您想要客户端验证 (JavaScript),请将 EnableClientScript 设置为 true:

    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBoxFirstName" EnableClientScript="true"></asp:RequiredFieldValidator>
    

    如果要在服务器上验证,请在代码隐藏中使用 Page.IsValid 属性:

    if(Page.IsValid)
    {
     ...
    }
    

    您也可以使用 ValidationSummary( 标签)来验证控件组

    【讨论】:

    • 谢谢!那么我应该将我的代码隐藏更改为这样吗? protected void Button_Click(object sender, EventArgs e) { if (Page.IsValid) { PanelNameForm.Visible = false; PanelThankYou.Visible = true; LabelThankYouName.Text = TextBoxFirstName.Text + " " + TextBoxLastName.Text + "!"; } }
    • 我添加了 EnableClientScript="true",然后运行它。它仍然让我将 FirstName 留空。
    【解决方案2】:

    只需将validationGroup 属性添加到requiredfieldvalidator 和您发回数据的按钮。它将防止文本框出现空白值。

    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBoxFirstName" ValidationGroup="v"></asp:RequiredFieldValidator>
    
    ..... // other code
    
    <asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click" ValidationGroup="v" />
    

    愿这对你有用:D

    【讨论】:

    • 我检查了你的代码。请在您的代码中替换它&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
    • 我们现在使用的是 HTML5,而不是回到 XHTML。
    • 我对html5了解不多。但我想建议你应该使用javascript。
    【解决方案3】:

    这是我如何使用 HTML5(您说您正在使用)进行必填字段验证的快速演示。

    页面后面的演示代码(.aspx.cs):

    using System;
    using System.Web.UI.WebControls;
    
    public partial class PgValidationDemo : System.Web.UI.Page
    {
        // bind page init
        // in the page constructor
        public PgValidationDemo()
        {
            this.Init += PgValidationDemo_Init;
        }
    
        // Bind our submit button click event
        private void PgValidationDemo_Init(object sender, EventArgs e)
        {
            cmdSubmit.Click += cmdSubmit_Click;
        }
    
        // handle the submit button
        // click event
        private void cmdSubmit_Click(object sender, EventArgs e)
        {
            // Tell the form to validate
            // fields in validation group
            // 'ValidationDemo'
            String vGroup = "ValidationDemo";
            vSummary.ValidationGroup = vGroup;
            Page.Validate(vGroup);
    
            // Call our fantastic convenience method
            // to check if a textbox has a value in it
            this.addRequiredFieldValidator(txtFirstName, vGroup, "FirstName is Required.");
    
            // If Page.IsValid
            // redirect to the 'thanks page'
            // if it isnt valid we don't need to
            // provide additional code because
            // the error messages will show in the
            // validation summary
            if (Page.IsValid)
            {
                //Redirect to Thanks for filling out survey
            }
        }
    
        // convenience method to add required
        // text validators to the form collection
        private void addRequiredFieldValidator(TextBox txt, String validationGroup, String errorMessage)
        {
            Page.Validators.Add(new CustomValidator()
            {
                IsValid = !String.IsNullOrWhiteSpace(txt.Text),
                ErrorMessage = errorMessage,
                ValidationGroup = validationGroup
            });
        }
    }
    

    演示页面 (.aspx)

    <%@ Page Language="C#" AutoEventWireup="false" CodeFile="default.aspx.cs" Inherits="PgValidationDemo" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Validation Demo</title>
    </head>
    <body>
        <form id="aspnetForm" runat="server">
        <asp:ValidationSummary runat="server" ID="vSummary" />
    
        <label>
            FirstName: 
            <asp:TextBox runat="server" ID="txtFirstName" required="required" />
            <!-- 
                required="required" is an html5 form attribute that prevents
                folks from submitting forms with blank values in textboxes.
                great stuff!
            -->
        </label>
        <div>
            <asp:Button runat="server" id="cmdSubmit" Text="Submit" />
        </div>
        </form>
    </body>
    </html>
    

    【讨论】:

    • 我的 Button_Click 方法中有这个,但即使我将 FirstName 留空,它仍然会将我带到谢谢页面:protected void Button_Click(object sender, EventArgs e) { if (Page. IsValid) { PanelNameForm.Visible = false; PanelThankYou.Visible = true; LabelThankYouName.Text = TextBoxFirstName.Text + " " + TextBoxLastName.Text + "!"; } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2014-12-06
    • 2018-09-21
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多