[removed] Determine which control caused postback

2019-08-09 05:34发布

I am currently developing a web site using ASP.NET 3.5. On a page there are some situations I don't want that a specific control will cause a postback to the server. I wrote a function to return false if that condition is met which will be called when the onsubmit-Event occurs. But I somehow need to determine which control will cause the postback, because the postback should be cancelled only if this specific control caused it under certain conditions. How it is possible to do that?

Thanks for your time.

2条回答
爷、活的狠高调
2楼-- · 2019-08-09 06:16

You may be able to use the ScriptManager.GetCurrent().AsyncPostBackSourceElementID to find the control that caused the postback to the page.

More details on MSDN but it will work in these instances:

  • A postback from a control that is inside an UpdatePanel control whose ChildrenAsTriggers property is set to true (the default).

  • A postback from a control that is a trigger for an UpdatePanel control.

  • A postback from a control that is registered by calling the RegisterAsyncPostBackControl method of the ScriptManager control.

I don't know if you're using UpdatePanels but it seems likely as this is the only situation I can think of where you'd need to know which control is causing the postback.

查看更多
我命由我不由天
3楼-- · 2019-08-09 06:28

See:

How does ASP.NET recognize the control responsible for handling the postback? When no controls referenced in the request body implement the IPostBackEventHandler interface, the page class looks for the __EVENTTARGET hidden field, if any. The contents of the field is assumed to be the ID of the control that caused the postback. If this control implements the IPostBackEventHandler interface, the RaisePostbackEvent method is invoked.

this is from here - The Client Side of ASP.NET Pages.

So at the client-side __EVENTTARGET is all you need. At the server-side you could either override the Page.RaisePostBackEvent method (this is protected method, so you could inherit from System.Web.UI.Page class):

protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, 
                                           string eventArgument)
{
    // sourceControl is a control that caused postback
    base.RaisePostBackEvent(sourceControl, eventArgument);
}

or perform the same without inherining:

var controlName = page.Request.Params["__EVENTTARGET"];
Control postbackControl = null;
if (!string.IsnullOrEmpty(controlName))
{
    postbackControl = this.Page.FindControl(controlName);
}

EDIT: regarding the author's comment to my answer: if __EVENTTARGET value is an empty string, it seems you're getting this value before it is been set in __doPostBack function. So the workaround could be in overriding __doPostBack function or a similar way; you could find an example of doing it in this SO quesion.

查看更多
登录 后发表回答