2007年9月17日 星期一

.NET RegisterForEventValidation and GetPostBackEventReference

It's convenient to use GetPostBackEventReference to force a postback from client side to a server control. However, in .NET 2.0, there is a catch; that is, the event will be validated for security reasons before the postback occurs. Therefore, you will likely get an error if you simply use the following code to force a postback to btn_Hidden1:

ClientScript.RegisterStartupScript(this.GetType(), "message",
ClientScript.GetPostBackEventReference(btn_Hidden1, ""), true);

One solution is to use RegisterForEventValidation. Then again, this method can only be called during the phase of page rendering. So we have to do the following:

protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(new PostBackOptions(btn_Hidden1));
base.Render(writer);
}

Another seemingly easier solution is to set the EnableEventValidation property for the page to false. (This can be done in the @Page directive) Also, you can do it in the application level by setting up the web.config accordingly. For example:

In the page level:

<%@ Page Language="C#" MasterPageFile="Plan.master" AutoEventWireup="true" EnableEventValidation="false" CodeFile="plan_CaseMain.aspx.cs" Inherits="Plan_CaseMain" Title="Untitled Page" MaintainScrollPositionOnPostback="true" %>

In the application level:

<pages validateRequest="false" />

Of course, the second and the third approaches are less preferable, cause they might create security holes in your page or application. The first one is more complicated, but more legid.

沒有留言: