使用gridview内的按钮导致ASP.net事件验证错误

时间:2014-07-15 04:02:02

标签: c# asp.net gridview

我有一个有多个按钮的页面。单击一个按钮时,一切都很好但是在它进行回发并单击另一个按钮后会产生异常:System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.

 这是aspx代码:

    <asp:GridView ID="gvSafeList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" OnRowCommand="gvSafeList_RowCommand" PageSize="15">
    <Columns>
        <asp:BoundField DataField="EmailTo" HeaderText="Account" SortExpression="EmailTo" />
        <asp:BoundField DataField="EmailFromName" HeaderText="From" SortExpression="EmailFromName" />
        <asp:BoundField DataField="EmailFrom" HeaderText="Senders Email" SortExpression="EmailFrom" />
        <asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />
        <asp:BoundField DataField="Time_Stamp" HeaderText="Time" SortExpression="Time_Stamp" />
        <asp:TemplateField>
          <ItemTemplate>
            <asp:Button ID="AddButton" runat="server" 
              CommandName="AddToSafeList" 
              CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
              Text="Unblock & Restore" />
          </ItemTemplate> 
        </asp:TemplateField>
    </Columns>
    <PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" NextPageText="Next" PageButtonCount="20" Position="TopAndBottom" PreviousPageText="Previous" />
    <PagerStyle Font-Bold="True" Font-Size="15pt" HorizontalAlign="Center" />
</asp:GridView>

这是我的c#代码:

    protected void gvSafeList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
       //Do some database stuff...
        if (e.CommandName == "AddToSafeList")
        {
//More stuff
            Response.Redirect("~/Spam",false);

            lblResults.Text = "Successfully updated. Emails from this recipient will be delivered to your inbox within the next 5 minutes.";
        }
    }
    catch (Exception ex)
    {
        LogIt(ex.ToString());

    }

}

Gridview Screenshot 我一直坚持这一点,设置event validation = false似乎对我来说太危险了。

1 个答案:

答案 0 :(得分:2)

你的Page_Load活动中有代码吗?如果是,那么也许通过添加以下内容将有所帮助。

if (!Page.IsPostBack)
{ 
    //do something
}

当您单击命令并再次运行Page_load时会抛出此错误,在正常生命周期中将是Page_Load - &gt;点击命令 - &gt; Page_Load(再次) - &gt;处理RowCommand事件