【问题标题】:How to get the Button & ImageButton controls using Request.Form["__EVENTTARGET"]如何使用 Request.Form["__EVENTTARGET"] 获取 Button 和 ImageButton 控件
【发布时间】:2013-09-30 07:26:02
【问题描述】:

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

那么,正如上面提到的文章使用了一个 hiddenField,Javascript 代码作为解决方法,有没有更优雅的方法来做到这一点??

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

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

【问题讨论】:

  • 您可以通过将Button 控件的UseSubmitBehavior 属性设置为false 来强制Button 控件使用javascript 提交到服务器。这样,您将在代码隐藏中拥有 __EVENTTARGET 值。但这不适用于ImageButton

标签: c# asp.net .net postback


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2019-02-13
    • 1970-01-01
    • 2011-01-19
    • 2023-03-30
    • 2015-04-09
    • 1970-01-01
    相关资源
    最近更新 更多