asp.net listbox событие двойного щелчка + обработчик события
Я пытаюсь добавить событие двойного щелчка в списке.
Но я получаю следующую ошибку.
файл aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListBox__Test.aspx.cs" Inherits="DataBind__Various_Controls.ListBox__Test" %>
<!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>
<asp:ListBox ID="ListBox1" runat="server" Height="207px" Width="167px" AutoPostBack="True">
</asp:ListBox>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="btnForListBoxDoubleClick" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
файл CS
namespace DataBind__Various_Controls
{
public partial class ListBox__Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string postbackRef = ClientScript.GetPostBackEventReference(btnForListBoxDoubleClick, "dblClickfromHiddenButton"); //this.Page.GetPostBackClientEvent(btnForListBoxDoubleClick, "dblClickfromHiddenButton");
ListBox1.Attributes.Add("onclick", postbackRef);
}
}
private void btnForListBoxDoubleClick_ServerClick(object sender, System.EventArgs e)
{
string argument = Request.Params["__EVENTARGUMENT"].Trim();
if (argument == "dblClickfromHiddenButton")
{
this.Label1.Text = "Hello!";
}
}
}
}
страница ошибки
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) +8620921
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +72
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +35
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) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053
Как я могу решить проблему?
1 ответ
Есть два способа избавиться от ошибки
1. Отключить проверку событий
Это просто, и все, что вам нужно сделать, это установить EnableEventValidation="false" в директиве страницы.
<%@ Page Language="C#" EnableEventValidation="false" EnableAutoEventWireup="true" CodeBehind="ListBox__Test.aspx.cs" Inherits="DataBind__Various_Controls.ListBox__Test" %>
Однако это не рекомендуется Microsoft ( настоятельно рекомендуется не отключать проверку событий. Если вы отключите проверку событий, убедитесь, что не может быть создана обратная передача, которая может оказать непреднамеренное влияние на ваше приложение.)
2. Зарегистрируйте свое событие
Вы можете зарегистрировать свой клиентский скрипт, переопределив метод Render. Обратите внимание, что "Render" - единственное место, где вам разрешено это делать.
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation("btnForListBoxDoubleClick",
"dblClickfromHiddenButton");
}
Это должно избавить от ошибки EnableEventValidation без необходимости отключения проверки события.
Надеюсь это поможет!
В качестве примечания, я не уверен, как вы подключаете обработчик событий btnForListBoxDoubleClick_ServerClick на своей странице. Как будет происходить это событие?