如何获得Button&使用Request.Form [“__ EVENTTARGET”]的ImageButton控件

时间:2013-09-30 07:26:03

标签: c# asp.net .net postback

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

因此,正如上面提到的文章使用hiddenField,Javascript代码进行解决方法,是否有更优雅的方法来做到这一点?

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

OR

Button / ImageButton的任何属性都会使它使用__doPostBack函数??

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

EventTargets.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文件的完整代码:

EventTargets.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"];
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我不知道你对它的优雅方式:)但它很容易......见..

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;
}