验证失败时推进按钮代码隐藏...如何在没有Page.IsValid的情况下解决它?

时间:2010-10-27 11:26:12

标签: c# javascript asp.net validation postback

我有一个ASP .NET页面,同时包含asp .net验证器和一些javascript检查。 我正在进入后面的按钮代码:

protected void Button2_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            /// ...

即使验证失败! Page.IsValid检查解决了它,但它也重置了所有的JavaScript变量......有没有办法不进入按钮代码? 我有一个ajax更新面板和页面上的一些图像按钮......我可能需要注意什么? 提前谢谢!

这是我的aspx:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs" 
Inherits="WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width: 500px;">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <script type="text/javascript">
            var nrOptions = 0;
            alert(nrOptions + " - variable initialized");
            function IncrementQuantity() {
                nrOptions++;
                alert(nrOptions);
            }
            function DecrementQuantity() {
                nrOptions--;
                alert(nrOptions);
            }
            function MoreThanTwo() {
                alert(nrOptions);
                if (nrOptions > 1) {
                    alert('okay - you have: ' + nrOptions);
                    return true;
                }
                else {
                    alert('error - must have at least two options, you only have: ' + nrOptions);
                    return false;
                }
            }            
        </script>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
                    <HeaderTemplate>
                        Fill in with two or more options:<br />
                        <table border="1" width="100%">
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td valign="middle">
                            </td>
                            <td valign="middle">
                                Description:
                                <asp:TextBox ID="TBox1" runat="server" Width="120px" Text='<%# Eval("Desc")%>'></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TBox1"
                                    ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
                                Points:
                                <asp:TextBox ID="TBox2" runat="server" Width="20px" Text='<%# Eval("Pont")%>'></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TBox2"
                                    ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
                                <asp:Button ID="ImageButton1" runat="server" Text="x" CommandName="DeleteRow" OnClientClick="DecrementQuantity();" />
                                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TBox2"
                                    ValidationExpression="\d+" ValidationGroup="InsertVal" runat="server"
                                    ErrorMessage="Number >= 0."></asp:RegularExpressionValidator>
                            </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>
                        <tr>
                            <td colspan="2" align="right">
                                <asp:Button ID="lnkAddRow" runat="server" Text="Add option" OnClientClick="IncrementQuantity();"
                                    CommandName="AddRow" OnClick="lnkAddRow_Click" />
                            </td>
                        </tr>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>
                <br />
                <p style="text-align: right;">
                    <asp:Button ID="Button2" runat="server" Text="Save" OnClick="Button2_Click" OnClientClick="return MoreThanTwo();"
                        ValidationGroup="InsertVal" />
                </p>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

我的代码隐藏:

使用System; 使用System.Collections.Generic; 使用System.Linq; 使用System.Web; 使用System.Web.UI; 使用System.Web.UI.WebControls; 使用System.Data;

public partial class WebForm2 : System.Web.UI.Page
{        

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DTable = EmptyDTOptions();
            Repeater1.DataSource = DTable;
            Repeater1.DataBind();
        }
    }

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

        if (e.CommandName == "AddRow")
        {
            DTable.Rows.Add(0, "", "");
            Repeater1.DataSource = DTable;
            Repeater1.DataBind();
            return;
        }

        if (e.CommandName == "DeleteRow")
        {

            int idx = e.Item.ItemIndex;
            DTable.Rows.RemoveAt(idx);
            Repeater1.DataSource = DTable;
            Repeater1.DataBind();
            return;
        }

    }

    protected void lnkAddRow_Click(object sender, EventArgs e)
    {
        foreach (RepeaterItem item in Repeater1.Items)
        {
            int idx = item.ItemIndex;

            TextBox tb1 = (TextBox)item.FindControl("TBox1");
            TextBox tb2 = (TextBox)item.FindControl("TBox2");

            DTable.Rows[idx]["Desc"] = tb1.Text;
            DTable.Rows[idx]["Pont"] = tb2.Text;
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {                
            // save!             
        }
    }

    private DataTable DTable
    {
        get
        {
            DataTable _dt = (DataTable)Session["DTable"];
            if (Object.Equals(_dt, null))
            {
                _dt = EmptyDTOptions();
                Session.Add("DTable", _dt);
            }
            return _dt;
        }
        set
        {
            Session["DTable"] = value;
        }
    }

    DataTable EmptyDTOptions()
    {
        DataTable dt = new DataTable();
        DataColumn dc;

        dc = new DataColumn("OptionNr", System.Type.GetType("System.Int32"));
        dt.Columns.Add(dc);
        dc = new DataColumn("Desc");
        dt.Columns.Add(dc);
        dc = new DataColumn("Pont");
        dt.Columns.Add(dc);

        return dt;
    }
}

我认为它显示了我想要避免的内容...使用失败的验证(并重置javascript变量)前进到button2_click ...为了获得两对或更多项的列表,他们是一个数字。

1 个答案:

答案 0 :(得分:1)

您可以添加一个调用JavaScript函数的CustomValidator,而不是从按钮上的OnClientClick调用函数。

<asp:CustomValidator ID="CheckMoreThanTwo" runat="server"                       
                     ValidationGroup="InsertVal"
                     ClientValidationFunction="MoreThanTwo" />

然后,按如下方式修改JavaScript函数:

function MoreThanTwo(source, arguments) {      
    alert(nrOptions);      
    if (nrOptions > 1) {      
        alert('okay - you have: ' + nrOptions);      
        arguments.IsValid=true;
    } else {      
        alert('error - must have at least two options, you only have: '
                  + nrOptions);      
        arguments.IsValid=false;
    }      
}                  

这样做可以使您的自定义JavaScript验证与ASP.NET使用的所有验证代码一起使用。例如,如果您更改为验证摘要或更改验证组,则此自定义验证程序将继续以其他验证程序的工作方式运行。