EVENTTARGET确定发件人的问题

时间:2011-04-18 14:36:13

标签: c# asp.net forms

我正在试图弄清楚点击了什么按钮,这段代码在IE中工作得很好,但如果我使用Chrome,Firefox或Safari,它什么都不做。在firefox中使用firebug时,我查看了Form Details,它显示EVENTTARGET没有任何值只是空白。如何才能在FF,Chrome和Safari上使用它?

方法:

       Control postbackControlInstance = null;

        string postbackControlName = page.Request.Params.Get("__EVENTTARGET");
        if (postbackControlName != null && postbackControlName != string.Empty)
        {
            postbackControlInstance = page.FindControl(postbackControlName);
        }
        else
        {
            for (int i = 0; i < page.Request.Form.Keys.Count; i++)
            {
                postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
                if (postbackControlInstance is System.Web.UI.WebControls.Button)
                {
                    return postbackControlInstance;
                }
            }
        }
        if (postbackControlInstance == null)
        {
            for (int i = 0; i < page.Request.Form.Count; i++)
            {
                if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y")))
                {
                    postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2));
                    return postbackControlInstance;
                }
            }
        }
        return postbackControlInstance;

代码呼叫方法:

        if (Page.IsPostBack)
        {
            try
            {
                Control cause = GetPostBackControl(Page);
                string statecause = cause.ID;
                if (statecause == "buttonName1")
                {
                    search(statecause);
                }
                else if (statecause == "buttonNAME2")
                {
                    resetfields();
                }
            }
            catch { }
        }

1 个答案:

答案 0 :(得分:3)

最好的方法是确定导致回发的控件是否覆盖protected Page.RaisePostBackEvent方法。 ASP.NET基础架构使用此方法来通知服务器控件,该控件导致回发它应该处理传入的回发事件:

public class MyPage : Page
{
    protected override void RaisePostBackEvent(
        IPostBackEventHandler sourceControl, 
        string eventArgument
    )
    {
        // here is the control that caused the postback
        var postBackControl = sourceControl;

        base.RaisePostBackEvent(sourceControl, eventArgument);
    }
}

当客户端__doPostBack函数呈现给页面时,您提供的代码应该适用于各种各样的代码(例如,如果您只使用<asp:Button runat="server" ID="btnSubmit" Text="submit" UseSubmitBehavior="true" />这样的一个按钮,那么它将不会被渲染)

即使在呈现__doPostBack函数的情况下,但__EVENTTARGET参数为空,也表示自定义/不兼容的javascript代码违反了__doPostBack函数的默认行为在大多数情况下。在这种情况下,即使ASP.NET基础结构也无法正确处理回发事件。