C# 错误:无效的回发或回调参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12444946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:18:29  来源:igfitidea点击:

Error: Invalid postback or callback argument

c#asp.netajaxbuttongridview

提问by cb1295

I am getting the following error on a button click with gridview

使用 gridview 单击按钮时出现以下错误

 Server Error in '/' Application.
Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +144
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +29
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

It occurs when I press a button inside the gridview, and the odd thing is that I have another gridview, also with custom button in a column that runs different code, but gives no errors. Below is the code for the page and the codebehind.

它发生在我按下 gridview 内的按钮时,奇怪的是我有另一个 gridview,也在运行不同代码的列中带有自定义按钮,但没有给出错误。下面是页面和代码隐藏的代码。

namespace CCCC
{
    public partial class drivermangement : System.Web.UI.MasterPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (Roles.IsUserInRole("Administrator"))
                {
                    LoggedInUser.Value = Convert.ToString(Request.QueryString["driver"]);
                }
                else
                {
                    LoggedInUser.Value = Membership.GetUser().UserName.ToString();
                }
                DayOfTheWeekHiddenField.Value = Convert.ToString(Request.QueryString["dow"]);
            }
            else
            {
                Response.Redirect("default.aspx");
            }
            if (NewCustomersGrid.Rows.Count == 0)
            {
                NewCustomersLabel.Visible = false;
            }
            else
            {
                NewCustomersLabel.Visible = true;
            }
            if (NeedCompostGrid.Rows.Count == 0)
            {
                NeedCompostLabel.Visible = false;
            }
            else
            {
                NeedCompostLabel.Visible = true;
            }
            if (CanceledGrid.Rows.Count == 0)
            {
                CanceledLabel.Visible = false;
            }
            else
            {
                CanceledLabel.Visible = true;
            }
            if (VacationGrid.Rows.Count == 0)
            {
                VacationLabel.Visible = false;
            }
            else
            {
                VacationLabel.Visible = true;
            }
            if (NewCustomersGrid0.Rows.Count == 0)
            {
                NewCustomersLabel0.Visible = false;
            }
            else
            {
                NewCustomersLabel0.Visible = true;
            }
            if (NeedCompostGrid0.Rows.Count == 0)
            {
                NeedCompostLabel0.Visible = false;
            }
            else
            {
                NeedCompostLabel0.Visible = true;
            }
            if (CanceledGrid0.Rows.Count == 0)
            {
                CanceledLabel0.Visible = false;
            }
            else
            {
                CanceledLabel0.Visible = true;
            }
        }

        protected void NewCustomerDoneButton_Click(object sender, EventArgs e)
        {
            int CustomerID = Convert.ToInt32(((Button)sender).CommandArgument);
            string CustomerBinNeedAcknowledged = "Yes";
            string strConnString = "Data Source";
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "UPDATE Customers SET CustomerBinNeedAcknowledged=@CustomerBinNeedAcknowledged WHERE CustomerID=@CustomerID";
                    cmd.Parameters.AddWithValue("@CustomerBinNeedAcknowledged", CustomerBinNeedAcknowledged);
                    cmd.Parameters.AddWithValue("@CustomerId", CustomerID);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            } 
       }

and the actual page:

和实际页面:

<%@ Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Inherits="CCCCCC.drivermangement" CodeBehind="drivermangement.master.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:HiddenField ID="LoggedInUser" runat="server" />
    <asp:HiddenField ID="DayOfTheWeekHiddenField" runat="server" />
    <ajaxToolkit:TabContainer ID="RoutingTabs" runat="server" ActiveTabIndex="0" 
        Width="900px">
        <ajaxToolkit:TabPanel runat="server" HeaderText="Pre-Route" ID="PreRouteTab">
        <ContentTemplate>
<br />
<asp:Label ID="NewCustomersLabel" runat="server" 
        style="font-weight: 700; font-size: large; color: #009933" Text="New Customers"></asp:Label>

<asp:GridView ID="NewCustomersGrid" runat="server" AllowPaging="True" AutoGenerateColumns="False" BackColor="White" 
        BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
        DataKeyNames="CustomerId" DataSourceID="NewCustomers" ForeColor="Black" 
        GridLines="Vertical">
<AlternatingRowStyle BackColor="#99FF99" ></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="CustomerFullName" HeaderText="Name" 
                SortExpression="CustomerFullName" />
<asp:BoundField DataField="CustomerFullAddress" HeaderText="Address" 
                SortExpression="CustomerFullAddress" />
<asp:BoundField DataField="CustomerNeedsBin" HeaderText="Needs Bin?" 
        SortExpression="CustomerNeedsBin" />
<asp:TemplateField ShowHeader="False"><ItemTemplate>
                <asp:Button ID="NewCustomerDoneButton" runat="server" CommandName="" 
                Text="Done" CommandArgument='<%# Eval("CustomerID") %>' OnClick="NewCustomerDoneButton_Click" CausesValidation="False" />

</ItemTemplate>
</asp:TemplateField>
</Columns>
<asp:SqlDataSource ID="NewCustomers" runat="server" 
        ConnectionString="<%$ ConnectionStrings:tcc_customersConnectionString %>" 

                SelectCommand="SELECT [CustomerId], [CustomerStatus], [CustomerFullName], [CompanyName], [CustomerFullAddress], [CustomerPickUpDay], [CustomerPickUpDay2], [CustomerDriver], [CustomerNeedsBin], [CustomerBinNeedAcknowledged] FROM [Customers] WHERE (([CustomerBinNeedAcknowledged] = @CustomerBinNeedAcknowledged) AND ([CustomerNeedsBin] = @CustomerNeedsBin) AND ([CustomerDriver] = @CustomerDriver) AND ([CustomerStatus] = @CustomerStatus) AND ([CustomerPickUpDay] = @CustomerPickUpDay OR [CustomerPickUpDay2] = @CustomerPickUpDay2))"><SelectParameters>
<asp:Parameter DefaultValue="No" Name="CustomerBinNeedAcknowledged" Type="String" />
<asp:Parameter DefaultValue="Yes" Name="CustomerNeedsBin" Type="String" />
<asp:ControlParameter ControlID="LoggedInUser" Name="CustomerDriver" 
            PropertyName="Value" Type="String"></asp:ControlParameter>
<asp:Parameter DefaultValue="New" Name="CustomerStatus" Type="String" />
<asp:ControlParameter ControlID="DayOfTheWeekHiddenField" Name="CustomerPickUpDay" 
                PropertyName="Value" Type="String" ></asp:ControlParameter>
<asp:ControlParameter ControlID="DayOfTheWeekHiddenField" 
            Name="CustomerPickUpDay2" PropertyName="Value" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

</ContentTemplate>

</ajaxToolkit:TabPanel>
        <ajaxToolkit:TabPanel runat="server" HeaderText="Post-Route" ID="PostRouteTab"><ContentTemplate>

I'm now wondering, does this have anything to do with the fact that the GridViewis inside an Ajax Tab Container? Cause my other table that works fine is not...

现在我想知道,这是否有什么关系的事实,GridView是内部的Ajax Tab Container?因为我的另一个工作正常的表不是......

Note: had to cut some code from page due to character limits

注意:由于字符限制,不得不从页面中删除一些代码

采纳答案by Pushpendra

1) Invalid Postback or Callback argument in GridView Problem may be: You are binding data in Page_Load event with either Object Data Source or Manual Binding with function call. This will make your GridView bind data on every event fire of any control.

1) GridView 中无效的回发或回调参数问题可能是:您正在使用对象数据源或手动绑定与函数调用绑定 Page_Load 事件中的数据。这将使您的 GridView 在任何控件的每个事件触发上绑定数据。

When you are firing any GridView command with OnRowCommand, before RowCommand fire your GridView will rebind and all control within it will be assigned to new id. So RowCommand could not get the item which have fired the event.

当您使用 OnRowCommand 触发任何 GridView 命令时,在 RowCommand 触发之前,您的 GridView 将重新绑定,并且其中的所有控件都将分配给新的 ID。所以 RowCommand 无法获取触发事件的项目。

Solution for Invalid Postback or Callback argument in GridView: You can bind your data within this if condition

GridView 中 Invalid Postback 或 Callback 参数的解决方案:你可以在这个 if 条件下绑定你的数据

if (!IsPostBack)
{
    //Your code for Bind data 
}

This code will definitely give you solution if this not work then check whether any other control is not giving error.

如果这不起作用,此代码肯定会为您提供解决方案,然后检查是否有任何其他控件没有给出错误。

回答by Pushpendra

are you updating the Grid or any such control through javascript or Ajax.

您是否通过 javascript 或 Ajax 更新网格或任何此类控件。

If this is the case then you might face this. Possible solution can be to set EnableEventValidation to false.

如果是这种情况,那么您可能会遇到这种情况。可能的解决方案是将 EnableEventValidation 设置为 false。

回答by NoviceProgrammer

A few things to try

一些尝试

  1. In your Page Loadevent, add a check for !Page.IsPostBackand move the non-authenticating code block there.
  2. Experiment using a LinkButtoninstead of a regular button.
  1. 在您的Page Load活动中,添加检查!Page.IsPostBack并将非身份验证代码块移动到那里。
  2. 尝试使用LinkButton代替常规按钮。

回答by Umer Hayat

This could be because of any third party controls you are using.

这可能是因为您使用了任何第三方控件。

I also had this error. In my case i have a repeater control inside updatepanel and inside repeater control i was using telerik datepicker control. It was working fine in IE but not in mozilla and chrome. I examined the form data in both the cases by sending request from chrome and IE and found that the triggring control values are slightly different. i used telerik RadAjaxmanager instead of updatepanel the error gone.

我也有这个错误。在我的情况下,我在 updatepanel 中有一个转发器控件,在转发器控件中我使用了 Telerik datepicker 控件。它在 IE 中运行良好,但在 mozilla 和 chrome 中却没有。我通过从 chrome 和 IE 发送请求检查了这两种情况下的表单数据,发现触发控件值略有不同。我使用了 Telerik RadAjaxmanager 而不是 updatepanel 错误消失了。

回答by Zolfaghari

I testing all above solutions and other posts but my problem isn't done.

我测试了上述所有解决方案和其他帖子,但我的问题没有解决。

My problem was solved when cancel event at end of grid event at server side.

在服务器端网格事件结束时取消事件时,我的问题得到了解决。

This type of problem occurred when we using edit event of gridview. just add e.Cancel = true; at the end of event.

当我们使用gridview的edit事件时出现这种类型的问题。只需添加 e.Cancel = true; 在活动结束时。

protected void grdEducation_RowEditing(object sender, GridViewEditEventArgs e)
{
  // do your processing ... 

  // at end     
  e.Cancel = true;
}