' 启用事件验证" />

回发或回调参数无效。 使用“' 启用事件验证

发布于 2024-07-07 01:22:34 字数 3142 浏览 7 评论 0 原文

当我从客户端回发页面时,出现以下错误。 我有修改客户端 asp:ListBox 的 JavaScript 代码。

我们该如何解决这个问题?

错误详细信息如下:

Server Error in '/XXX' 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) +2132728
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
   System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.

How do we fix this?

Error details below:

Server Error in '/XXX' 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) +2132728
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
   System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

半暖夏伤 2024-07-14 01:22:35

如果您预先知道可以填充的数据,则可以使用 ClientScriptManager 来解决此问题。 我在以前的用户选择上使用 javascript 动态填充下拉框时遇到了这个问题。

下面是一些示例代码,用于覆盖渲染方法(在 VB 和 C# 中)并声明下拉列表 ddCar 的潜在值。

在 VB 中:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

    Dim ClientScript As ClientScriptManager = Page.ClientScript

    ClientScript.RegisterForEventValidation("ddCar", "Mercedes")

    MyBase.Render(writer)
End Sub

或 C# 中的细微变化可能是:

protected override void Render(HtmlTextWriter writer)
{
    Page.ClientScript.RegisterForEventValidation("ddCar", "Mercedes");
    base.Render(writer);
}

对于新手:这应该放在文件后面的代码中(.vb 或 .cs),或者如果在 aspx 文件中使用,您可以将其包装在

If you know up front the data that could be populated, you can use the ClientScriptManager to resolve this issue. I had this issue when dynamically populating a drop down box using javascript on a previous user selection.

Here is some example code for overriding the render method (in VB and C#) and declaring a potential value for the dropdownlist ddCar.

In VB:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

    Dim ClientScript As ClientScriptManager = Page.ClientScript

    ClientScript.RegisterForEventValidation("ddCar", "Mercedes")

    MyBase.Render(writer)
End Sub

or a slight variation in C# could be:

protected override void Render(HtmlTextWriter writer)
{
    Page.ClientScript.RegisterForEventValidation("ddCar", "Mercedes");
    base.Render(writer);
}

For newbies: This should go in the code behind file (.vb or .cs) or if used in the aspx file you can wrap in <script> tags.

最初的梦 2024-07-14 01:22:35

这就是我得到它的原因:

我有一个 ASP:ListBox。 最初它是隐藏的。 在客户端,我将通过 AJAX 使用选项填充它。 用户选择了一个选项。 然后,当单击“提交”按钮时,服务器会对列表框感到很奇怪,因为它不记得它有任何选项。

所以我所做的就是确保在将表单提交回服务器之前清除所有列表选项。 这样服务器就不会抱怨,因为列表发送到客户端时是空的,返回时也是空的。

已排序!!!

This was the reason why I was getting it:

I had an ASP:ListBox. Initially it was hidden. At client side I would populate it via AJAX with options. The user chose one option. Then when clicking the Submit button, the Server would get all funny about the ListBox, since it did not remember it having any options.

So what I did is to make sure I clear all the list options before submitting the form back to the server. That way the server did not complain since the list went to the client empty and it came back empty.

Sorted!!!

莫言歌 2024-07-14 01:22:34

在本例中,将 id 添加到网格 RowDataBound 中的按钮。 它会解决你的问题。

In this case add id to the button in RowDataBound of the grid. It will solve your problem.

北方的韩爷 2024-07-14 01:22:34

Ajax UpdatePanel 做到了,我认为这是最简单的方式,忽略了Ajax 回发开销。

Ajax UpdatePanel makes it, and I think it's the easiest way, ignoring the Ajax postback overhead.

醉酒的小男人 2024-07-14 01:22:34

我知道这是一个超级旧的帖子。 假设您正在调用您的应用程序,这里有一个对我有用的想法:

  1. 在您的页面上实现 ICallbackEventHandler
  2. 调用 ClientScriptManager.GetCallbackEventReference 来调用您的服务器端代码
  3. 正如错误消息所述,您可以调用 ClientScriptManager.RegisterForEventValidation

如果您不需要完全控制,您可以使用更新面板来为您完成此操作。

I know that this is a super-old post. Assuming that you are calling into your application, here is an idea that has worked for me:

  1. Implement the ICallbackEventHandler on your page
  2. Call ClientScriptManager.GetCallbackEventReference to call your server side code
  3. As the error message states, you could then call ClientScriptManager.RegisterForEventValidation

If you don't need total control, you could use an update panel which would do this for you.

混吃等死 2024-07-14 01:22:34

就会显示此错误:

如果没有回发添加代码

If(!IsPostBack){

 //do something

}

This error will show without postback

Add code:

If(!IsPostBack){

 //do something

}
夏有森光若流苏 2024-07-14 01:22:34

我也遇到了同样的问题,我做了什么:

只需添加一个条件 if(!IsPostBack) 即可正常工作:)

I've had the same problem, what I did:

Just added a condition if(!IsPostBack) and it works fine :)

豆芽 2024-07-14 01:22:34

如果您将 UseSubmitBehavior="True" 更改为 UseSubmitBehavior="False" 您的问题将得到解决

<asp:Button ID="BtnDis" runat="server" CommandName="BtnDis" CommandArgument='<%#Eval("Id")%>' Text="Discription" CausesValidation="True" UseSubmitBehavior="False" />

if you change UseSubmitBehavior="True" to UseSubmitBehavior="False" your problem will be solved

<asp:Button ID="BtnDis" runat="server" CommandName="BtnDis" CommandArgument='<%#Eval("Id")%>' Text="Discription" CausesValidation="True" UseSubmitBehavior="False" />
自在安然 2024-07-14 01:22:34

此问题的一个简单解决方案是对页面加载使用 IsPostBack 检查。 这将解决这个问题。

A simple solution for this problem is to use the IsPostBack check on your page load. That will solve this problem.

夜巴黎 2024-07-14 01:22:34

当我们将常规 ASPX 页面转换为内容页面时,我们遇到了同样的问题。

存在此问题的页面的内容部分之一内有一个 标记,因此在运行时呈现两个表单结束标记,从而导致了此问题。 从页面中删除额外的表单结束标记解决了此问题。

We ran into this same issue when we were converting our regular ASPX pages to Content pages.

The page with this issue had a </form> tag within one of the Content sections, thus two form end tags were rendered at run time which caused this issue. Removing the extra form end tag from the page resolved this issue.

柒七 2024-07-14 01:22:34

我在使用 Repeater 时遇到了同样的问题,因为我在打开了 EnableEventValidation 的网站中有一个带有 Repeater 控件的网页。 这不太好。 我收到与无效回发相关的异常。

对我有用的是为中继器设置 EnableViewState="false" 。 优点是使用起来更简单,就像关闭网站或网页的事件验证一样简单,但范围比关闭其中任何一个的事件验证要小得多。

I had the same problem with a Repeater because I had a web-page with a Repeater control in a web-site which had EnableEventValidation switched on. It wasn't good. I was getting invalid postback related exceptions.

What worked for me was to set EnableViewState="false" for the Repeater. The advantages are that it is simpler to use, as simple as switching event validation off for the web-site or web-page, but the scope is a lot less than switching event validation off for either.

梦境 2024-07-14 01:22:34

我遇到了类似的问题,但我没有使用 ASP.Net 1.1,也没有通过 javascript 更新控件。
我的问题只发生在 Firefox 上,而不是 IE 上(!)。

我在 PreRender 事件上向 DropDownList 添加了选项,如下所示:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string[] opcoes = HF.value.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

我的“HF”(隐藏字段)的选项由换行符分隔,如下所示:

HF.value = "option 1\n\roption 2\n\roption 3";

问题是 HTML 页面在选项上被破坏(我的意思是有换行符)代表下拉菜单的“选择”。

所以我解决了我的问题,添加一行:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string dados = HF.Value.Replace("\r", "");
string[] opcoes = dados.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

希望这对某人有帮助。

I had a similar issue, but I was not using ASP.Net 1.1 nor updating a control via javascript.
My problem only happened on Firefox and not on IE (!).

I added options to a DropDownList on the PreRender event like this:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string[] opcoes = HF.value.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

My "HF" (hiddenfield) had the options separated by the newline, like this:

HF.value = "option 1\n\roption 2\n\roption 3";

The problem was that the HTML page was broken (I mean had newlines) on the options of the "select" that represented the DropDown.

So I resolved my my problem adding one line:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string dados = HF.Value.Replace("\r", "");
string[] opcoes = dados.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

Hope this help someone.

深居我梦 2024-07-14 01:22:34

我实现了一个嵌套网格视图,我遇到了同样的问题。我使用 LinkBut​​ton 而不是像这样的图像按钮:

在我有这样的列之前:

<asp:TemplateField ItemStyle-Width="9">
  <ItemTemplate>
 <asp:ImageButton ID="ImgBtn" ImageUrl="Include/images/gridplus.gif" CommandName="Expand"
                        runat="server" />
  </ItemTemplate>
</asp:TemplateField>

我已经像这样替换了。

<asp:TemplateField>
<ItemTemplate>
     <asp:LinkButton  CommandName="Expand" ID="lnkBtn"  runat="server" ><asp:Image  ID="Img"  runat="server" ImageUrl="~/Images/app/plus.gif" /></asp:LinkButton>
      </ItemTemplate>
</asp:TemplateField> 

I implemented a nested grid view and i faced the same problem .I have used LinkButton instead of image button like this:

before i had a column like this:

<asp:TemplateField ItemStyle-Width="9">
  <ItemTemplate>
 <asp:ImageButton ID="ImgBtn" ImageUrl="Include/images/gridplus.gif" CommandName="Expand"
                        runat="server" />
  </ItemTemplate>
</asp:TemplateField>

I have replaced like this.

<asp:TemplateField>
<ItemTemplate>
     <asp:LinkButton  CommandName="Expand" ID="lnkBtn"  runat="server" ><asp:Image  ID="Img"  runat="server" ImageUrl="~/Images/app/plus.gif" /></asp:LinkButton>
      </ItemTemplate>
</asp:TemplateField> 
╄→承喏 2024-07-14 01:22:34

(1) EnableEventValidation="false"............它对我不起作用。

(2) ClientScript.RegisterForEventValidation...它对我不起作用。

解决方案1:

将GridView中的Button/ImageButton更改为LinkBut​​ton。 有用。 (不过我喜欢ImageButton)

研究:Button/ImageButton和LinkBut​​ton使用不同的方式回发

原文:

http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx

解决方案 2:

在 OnInit() 中,输入代码像这样为 Button/ImageButton 设置唯一 ID:

protected override void OnInit(EventArgs e) {
  foreach (GridViewRow grdRw in gvEvent.Rows) {

  Button deleteButton = (Button)grdRw.Cells[2].Controls[1];

  deleteButton.ID = "btnDelete_" + grdRw.RowIndex.ToString();           
  }
}

原始文章:

http:// www.c-sharpcorner.com/Forums/Thread/35301/

(1) EnableEventValidation="false"...................It does not work for me.

(2) ClientScript.RegisterForEventValidation....It does not work for me.

Solution 1:

Change Button/ImageButton to LinkButton in GridView. It works. (But I like ImageButton)

Research: Button/ImageButton and LinkButton use different methods to postback

Original article:

http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx

Solution 2:

In OnInit() , enter the code something like this to set unique ID for Button/ImageButton :

protected override void OnInit(EventArgs e) {
  foreach (GridViewRow grdRw in gvEvent.Rows) {

  Button deleteButton = (Button)grdRw.Cells[2].Controls[1];

  deleteButton.ID = "btnDelete_" + grdRw.RowIndex.ToString();           
  }
}

Original Article:

http://www.c-sharpcorner.com/Forums/Thread/35301/

错々过的事 2024-07-14 01:22:34

3:我更改了网格中的按钮类型
列从“PushButton”到
“链接按钮”。 有效!
("ButtonType="LinkBut​​ton") 我想如果
您可以将按钮更改为其他按钮
其他控件如“LinkBut​​ton”
情况下,它会正常工作。

我希望我能投票给你,阿米尔(唉,我的代表太低了。)我只是遇到了这个问题,并且在我的 gridview 上改变它就像冠军一样工作。 顺便说一句,我认为有效的代码是: ButtonType="Link"

我怀疑这是因为当您单击“编辑”时,您的编辑更改为“更新”和“取消”,然后在提交时更改回“编辑” 。 这些不断变化的控制让 .net 感到不安。

3: I changed my button type in grid
column from "PushButton" to
"LinkButton". It worked!
("ButtonType="LinkButton") I think if
you can change your button to other
controls like "LinkButton" in other
cases, it would work properly.

I wish I could vote you up, Amir (alas my rep is too low.) I was just having this problem and changing this worked like a champ on my gridview. Just a little aside, I think the valid code is: ButtonType="Link"

I suspect this is because when you click 'edit', your edit changes to 'update' and 'cancel' which then change back to 'edit' on submit. And these shifting controls make .net uneasy.

成熟的代价 2024-07-14 01:22:34

如果您通过客户端脚本填写 DropdownList,则在将表单提交回服务器之前清除列表; 那么 ASP.NET 就不会抱怨并且安全性仍然有效。

要获取从 DDL 中选择的数据,您可以将“OnChange”事件附加到 DDL,以收集隐藏输入或 Style="display: none;" 文本框中的值。

If you fill the DropdownList through client side script then clear the list before submit the form back to server; then ASP.NET will not complain and the security will be still on.

And to get the data selected from the DDL, you can attach an "OnChange" event to the DDL to collect the value in a hidden Input or in a textbox with Style="display: none;"

世态炎凉 2024-07-14 01:22:34

你尝试类似的方法,在你的 .aspx 页面中

添加

EnableEventValidation="false"

您可以随意提出任何问题!

you try something like that,in your .aspx page

add

EnableEventValidation="false"

you feel free to ask any question!

断肠人 2024-07-14 01:22:34

这里没有提到的另一种方法是子类化 ListBox

Ie。

public class ListBoxNoEventValidation : ListBox 
{
}

如果您将 ClientEventValidation 子类化,则 ClientEventValidation 将关闭属性 System.Web.UI.SupportsEventValidation,除非您显式地将其添加回来,否则它将永远不会调用验证例程。 这适用于任何控件,并且是我发现的在逐个控件的基础上“禁用”它的唯一方法(即,不是页面级别)。

One other way not mentioned here is to subclass ListBox

Ie.

public class ListBoxNoEventValidation : ListBox 
{
}

ClientEventValidation keys off the attribute System.Web.UI.SupportsEventValidation if you subclass it, unless you explicitly add it back in, it will never call the validation routine. That works with any control, and is the only way I've found to "disable" it on a control by control basis (Ie, not page level).

浪漫人生路 2024-07-14 01:22:34

在客户端使用 JavaScript 修改 ListBox 时,我遇到了同样的问题。 当您从客户端向 ListBox 添加新项目(在呈现页面时不存在)时,就会发生这种情况。

我发现的修复方法是通知事件验证系统可以从客户端添加的所有可能的有效项目。 您可以通过重写 Page.Render 并为 JavaScript 可以添加到列表框中的每个值调用 Page.ClientScript.RegisterForEventValidation 来完成此操作:

protected override void Render(HtmlTextWriter writer)
{
    foreach (string val in allPossibleListBoxValues)
    {
        Page.ClientScript.RegisterForEventValidation(myListBox.UniqueID, val);
    }
    base.Render(writer);
}

如果列表框有大量可能有效的值,这可能会很麻烦。 就我而言,我在两个列表框之间移动项目 - 一个列表框具有所有可能的值,另一个列表框最初为空,但当用户单击按钮时,会填充 JavaScript 中第一个列表框的值的子集。 在这种情况下,您只需迭代第一个列表框中的项目并将每个项目注册到第二个列表框:

protected override void Render(HtmlTextWriter writer)
{
    foreach (ListItem i in listBoxAll.Items)
    {
        Page.ClientScript.RegisterForEventValidation(listBoxSelected.UniqueID, i.Value);
    }
    base.Render(writer);
}

I had the same problem when modifying a ListBox using JavaScript on the client. It occurs when you add new items to the ListBox from the client that were not there when the page was rendered.

The fix that I found is to inform the event validation system of all the possible valid items that can be added from the client. You do this by overriding Page.Render and calling Page.ClientScript.RegisterForEventValidation for each value that your JavaScript could add to the list box:

protected override void Render(HtmlTextWriter writer)
{
    foreach (string val in allPossibleListBoxValues)
    {
        Page.ClientScript.RegisterForEventValidation(myListBox.UniqueID, val);
    }
    base.Render(writer);
}

This can be kind of a pain if you have a large number of potentially valid values for the list box. In my case I was moving items between two ListBoxes - one that that has all the possible values and another that is initially empty but gets filled in with a subset of the values from the first one in JavaScript when the user clicks a button. In this case you just need to iterate through the items in the first ListBoxand register each one with the second list box:

protected override void Render(HtmlTextWriter writer)
{
    foreach (ListItem i in listBoxAll.Items)
    {
        Page.ClientScript.RegisterForEventValidation(listBoxSelected.UniqueID, i.Value);
    }
    base.Render(writer);
}
能否归途做我良人 2024-07-14 01:22:34

四分钟前我收到了同样的错误。 然后我和你一样研究了一个半小时。 在所有论坛中,他们通常都会说“添加页面enableEvent..= false 或 true”。 在我找到它之前,提出的任何解决方案都无法解决我的问题。 不幸的是,问题出在 ASP.NET 按钮上。 两秒前我把它删除了。 我尝试用“imagebutton”替换,但它也是不可接受的(因为它给出了相同的错误)。

最后我用 LinkBut​​ton 替换了。 似乎正在发挥作用!

Four minutes ago I received the same error. Then I have researched during one half hour like you. In all forums they are generally saying "add page enableEvent..=false or true". Any solution proposed didn't resolved my problems until I found it. The problem is unfortunately an ASP.NET button. I removed it two seconds ago. I tried to replace with "imagebutton", but it was also unacceptable (because it gave the same error).

Finally I have replaced with LinkButton. it seems to be working!

奶气 2024-07-14 01:22:34

我正在使用 datalist,但我的按钮遇到了同样的错误。 我只是使用 IsPostBack 检查并填充我的控件,问题就解决了! 伟大的!!!

I was using datalist and I was getting the same error for my push button. I just use IsPostBack to check and fill my controls and the problem is solved! Great!!!

停滞 2024-07-14 01:22:34

对我有用的是将以下代码从 page_load 移动到 page_prerender:

lstMain.DataBind();
Image img = (Image)lstMain.Items[0].FindControl("imgMain");

// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
    cs.RegisterStartupScript(cstype, csname1, "<script language=javascript> p=\"" + img.ClientID + "\"</script>");
}

What worked for me is moving the following code from page_load to page_prerender:

lstMain.DataBind();
Image img = (Image)lstMain.Items[0].FindControl("imgMain");

// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
    cs.RegisterStartupScript(cstype, csname1, "<script language=javascript> p=\"" + img.ClientID + "\"</script>");
}
喜爱皱眉﹌ 2024-07-14 01:22:34

最好的选择是使用隐藏字段并且不要禁用事件验证,还更改每个列表框、下拉列表以使用 runat 服务器属性进行选择

Best option to do is use hidden field and do not disable event validation, also change every listbox, dropdownlist to select with runat server attribute

指尖上的星空 2024-07-14 01:22:34

如果您使用 Ajax 更新面板。 添加 标记,并在其内部使用 触发导致回发的按钮或控件

If you are using Ajax update panel. Add <Triggers> tag and inside it trigger the Button or control causing the postBack using <asp:PostBackTrigger .../>

虫児飞 2024-07-14 01:22:34

如果您使用 gridview 并且未在 !ispostback 内的页面加载时绑定 gridview ,那么当您单击 gridview 中的编辑和删除行时会发生此错误。

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        bindGridview();
        }

If you are using gridview and not bind gridview at pageload inside !ispostback then this error occur when you click on edit and delete row in gridview .

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        bindGridview();
        }
烙印 2024-07-14 01:22:34

以上都不适合我。 经过更多挖掘后,我意识到我忽略了导致问题的页面上应用的 2 个表单。

<body>
<form id="form1" runat="server">
<div>
        <form action="#" method="post" class="form" role="form">
        <div>
        ...
        <asp:Button ID="submitButton" runat="server"
        </div>
</div>
</body>

请注意,最近 ASP.NET 已开始考虑在表单标记内使用 iframe,其中 iframe 文档本身包含表单标记作为嵌套框架。 我必须将 iframe 移出表单标记才能避免此错误。

None of the above worked for me. After more digging I realized I had overlooked 2 forms applied on the page which was causing the issue.

<body>
<form id="form1" runat="server">
<div>
        <form action="#" method="post" class="form" role="form">
        <div>
        ...
        <asp:Button ID="submitButton" runat="server"
        </div>
</div>
</body>

Be aware that recently ASP.NET has started considering iframes within a form tag which contains a form tag in the iframe document itself a nested frame. I had to move the iframe out of the form tag to avoid this error.

孤城病女 2024-07-14 01:22:34

您确实需要执行 2 或 3 项操作,但不要禁用事件验证。

将项目添加到 asp:listbox 客户端有两个主要问题。

  • 首先是它会干扰事件验证。 返回到服务器的内容并不是它发送下来的内容。

  • 第二个是,即使您禁用事件验证,当您的页面被回发时,列表框中的项目也将从视图状态中重建,因此您在客户端上所做的任何更改都会丢失。 原因是 asp.net 不期望在客户端上修改列表框的内容,它只期望进行选择,因此它会丢弃您可能所做的任何更改。

最好的选择是最有可能使用建议的更新面板。 如果您确实需要在客户端执行此操作,另一种选择是使用普通的旧

然后,当您准备好发布它时,您可以从修改后的

总而言之,这是一个非常麻烦的解决方案,我不会真正推荐,但如果您确实必须对列表框进行客户端修改,那么它确实有效。 不过,我真的建议您在走这条路线之前先查看一下 updatePanel。

You are really going to want to do 2 or 3, don't disable event validation.

There are two main problems with adding items to an asp:listbox client side.

  • The first is that it interferes with event validation. What came back to the server is not what it sent down.

  • The second is that even if you disable event validation, when your page gets posted back the items in the listbox will be rebuilt from the viewstate, so any changes you made on the client are lost. The reason for this is that a asp.net does not expect the contents of a listbox to be modified on the client, it only expects a selection to be made, so it discards any changes you might have made.

The best option is most likely to use an update panel as has been recommended. Another option, if you really need to do this client side, is to use a plain old <select> instead of an <asp:ListBox>, and to keep your list of items in a hidden field. When the page renders on the client you can populate it from a split of your text field contents.

Then, when you are ready to post it, you repopulate the hidden field's contents from your modified <select>. Then, of course, you have to split that again on the server and do something with your items, since your select is empty now that it's back on the server.

All in all it's a pretty cumbersome solution that I would not really recommend, but if you really have to do client-side modifications of a listBox, it does work. I would really recommend you look into an updatePanel before going this route, however.

银河中√捞星星 2024-07-14 01:22:34

我有过使用 DataGrid 的经历。 其中一栏是“选择”按钮。 当我单击任何行的“选择”按钮时,我收到了此错误消息:

“无效的回发或回调参数。使用配置或
<%@ Page EnableEventValidation="true" %> 在一个页面中。 出于安全目的,此功能验证回发或的参数
回调事件源自最初呈现它们的服务器控件。 如果数据有效且符合预期,请使用
ClientScriptManager.RegisterForEventValidation 方法,以便注册回发或回调数据以进行验证。”

我改了几处代码,终于成功了。我的经验路线:

1)我将页面属性更改为 EnableEventValidation="false" 但它不起作用。(这不仅危险)
出于安全原因,未调用我的事件处理程序:void Grid_SelectedIndexChanged(object sender, EventArgs e)

2) 我在 Render 方法中实现了 ClientScript.RegisterForEventValidation但它不起作用。

protected override void Render(HtmlTextWriter writer)
{
    foreach (DataGridItem item in this.Grid.Items)
    {
        Page.ClientScript.RegisterForEventValidation(item.UniqueID);
        foreach (TableCell cell in (item as TableRow).Cells)
        {
            Page.ClientScript.RegisterForEventValidation(cell.UniqueID);
            foreach (System.Web.UI.Control control in cell.Controls)
            {
                if (control is Button)
                    Page.ClientScript.RegisterForEventValidation(control.UniqueID);
            }
        }
    }
}

3) 我将网格列中的按钮类型从 PushButton 更改为 LinkBut​​ton它起作用了!(“ButtonType =“LinkBut​​ton”)。我认为如果您可以将按钮更改为其他控件,例如在其他情况下“LinkBut​​ton”,它会正常工作。

I had an experience with DataGrid. One of it's columns was "Select" button. When I was clicking "Select" button of any row I had received this error message:

"Invalid postback or callback argument. Event validation is enabled using 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."

I changed several codes, and finally I succeeded. My experience route:

1) I changed page attribute to EnableEventValidation="false". But it didn't work. (not only is this dangerous
for security reason, my event handler wasn't called: void Grid_SelectedIndexChanged(object sender, EventArgs e)

2) I implemented ClientScript.RegisterForEventValidation in Render method. But it didn't work.

protected override void Render(HtmlTextWriter writer)
{
    foreach (DataGridItem item in this.Grid.Items)
    {
        Page.ClientScript.RegisterForEventValidation(item.UniqueID);
        foreach (TableCell cell in (item as TableRow).Cells)
        {
            Page.ClientScript.RegisterForEventValidation(cell.UniqueID);
            foreach (System.Web.UI.Control control in cell.Controls)
            {
                if (control is Button)
                    Page.ClientScript.RegisterForEventValidation(control.UniqueID);
            }
        }
    }
}

3) I changed my button type in grid column from PushButton to LinkButton. It worked! ("ButtonType="LinkButton"). I think if you can change your button to other controls like "LinkButton" in other cases, it would work properly.

上课铃就是安魂曲 2024-07-14 01:22:34

问题是 ASP.NET 无法了解这个额外的或删除的列表项。
您有许多选项(如下所列):

  • 禁用事件验证(坏主意,因为您会损失一点安全性,而成本却很少)。
  • 使用 ASP.NET Ajax UpdatePanel。 (如果添加或删除列表框,则将列表框放入 Updatepanel 并触发更新。这样视图状态和相关字段就会更新,并且事件验证将通过。)
  • 忘记客户端并使用经典的回发并添加或删除列表项服务器 -边。

The problem is that ASP.NET does not get to know about this extra or removed listitem.
You got an number of options (listed below):

  • Disable eventvalidation (bad idea, because you lose a little of security that come with very little cost).
  • Use ASP.NET Ajax UpdatePanel. (Put the listbox in the Updatepanel and trigger a update, if you add or remove listbox. This way viewstate and related fields get updates and eventvalidation will pass.)
  • Forget client-side and use the classic postback and add or remove the listitems server-side.
谎言 2024-07-14 01:22:34

您的 Page_Load 事件中有代码吗? 如果是,那么添加以下内容也许会有所帮助。

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

当您单击命令并且再次运行 Page_load 时,会引发此错误,在正常生命周期中,它会是
页面加载-> 点击命令-> Page_Load(再次)-> 处理项目命令事件

Do you have code in your Page_Load events? if yes, then perhaps adding the following will help.

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

This error is thrown when you click on your command and the Page_load is being ran again, in a normal life cycle it would be
Page_Load -> Click on Command -> Page_Load (again) -> Process ItemCommand Event

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文