2

当找到导致回发的控件时,<asp:ImageButton>&<asp:Button> 是例外,因为它们不使用__doPostBack函数。这一事实也得到了支持this Article

因此,正如上面指出的文章使用 hiddenField,Javascript 代码作为解决方法,有没有更优雅的方法来做到这一点?

我想要的是在使用 Button/ImageButton 控件时,我仍然想用Request.Form["__EVENTTARGET"]某种方式获取控件名称。有什么我需要知道的设置吗?

或者

Button / ImageButton 的任何属性都会使其使用该__doPostBack功能?

下面是我正在尝试的代码::

事件目标.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="EventTargets.aspx.cs" Inherits="EventTargets" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Button ID="btnAdd" runat="server" Text="Add"
     ClientIDMode="Static"/>
</asp:Content>

还有我的cs文件的完整代码:

事件目标.aspx.cs

public partial class EventTargets: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            string CtrlID = string.Empty;
            // for Button Controls, this is always string.Empty
            // and therefore it doesn't goes inside IF statement
            if (Request.Form["__EVENTTARGET"] != null &&
                Request.Form["__EVENTTARGET"] != string.Empty)
            {
                CtrlID = Request.Form["__EVENTTARGET"];
            }
        }
    }
}
4

1 回答 1

1

我不知道它是否适合你的优雅方式:) 但这很容易..see..

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        Control c = GetPostBackControl(this.Page);

        string ctrlId = c.ID;
    }
}

 private Control GetPostBackControl(Page page)
{
    Control control = null;

    string postBackControlName = Request.Params.Get("__EVENTTARGET");

    string eventArgument = Request.Params.Get("__EVENTARGUMENT");
    if (postBackControlName != null && postBackControlName.Length > 0)
    {
        control = Page.FindControl(postBackControlName);
    }

    else
    {
        foreach (string str in Request.Form)
        {
            Control c = Page.FindControl(str);
            if (c is Button)
            {
                control = c;
                break;
            }
        }
    }

    return control;
}
于 2013-10-01T08:53:34.247 回答