c# - __EVENTTARGET 在按钮点击回发时为空

标签 c# asp.net

我在aspx页面上有一个按钮

<asp:Button runat="server" CssClass="sc-ButtonHeightWidth" ID="btnFirstSave" Text="Save" OnClick="btnSave_Click" />

我正在尝试在代码中获取事件目标和事件源,以基于它进行一些验证。我尝试使用以下代码。

string ctrlname = page.Request.Params.Get("__EVENTTARGET");
string ctrlname = Request.Form["__EVENTTARGET"];
string ctrlname = Request.Params["__EVENTTARGET"];

但以上所有内容都给了我空值。如何获取每次导致回发的控件。我在上面做错了吗?

仅供引用:我已经尝试过此 LINK 中提到的解决方案.但它对我来说只是返回按钮文本。我想要按钮 ID。

最佳答案

Asp 按钮呈现为类型为 submitinput 此方法不会填充 _EVENTTARGET 使用 "__doPostBack" 方法引起回发的控件会将值添加到 _EVENTTARGET 因此 _EVENTTARGET 中缺少您的按钮 ID 您可以遍历页面中的所有控件以检查哪个控件导致回发。

试试这个来捕获您的控制权 - Here

private string getPostBackControlName()
        {
            Control control = null;
            //first we will check the "__EVENTTARGET" because if post back made by       the controls
            //which used "_doPostBack" function also available in Request.Form collection.
            string ctrlname = Page.Request.Params["__EVENTTARGET"];
            if (ctrlname != null && ctrlname != String.Empty)
            {
                control = Page.FindControl(ctrlname);
            }
            // if __EVENTTARGET is null, the control is a button type and we need to
            // iterate over the form collection to find it
            else
            {
                string ctrlStr = String.Empty;
                Control c = null;
                foreach (string ctl in Page.Request.Form)
                {
                    //handle ImageButton they having an additional "quasi-property" in their Id which identifies
                    //mouse x and y coordinates
                    if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                    {
                        ctrlStr = ctl.Substring(0, ctl.Length - 2);
                        c = Page.FindControl(ctrlStr);
                    }
                    else
                    {
                        c = Page.FindControl(ctl);
                    }
                    if (c is System.Web.UI.WebControls.Button ||
                             c is System.Web.UI.WebControls.ImageButton)
                    {
                        control = c;
                        break;
                    }
                }
            }
            return control.ID;

        }

关于c# - __EVENTTARGET 在按钮点击回发时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20838022/

相关文章:

c# - DDD 投屏问题?

c# - 如何查看HttpWebRequest发送的headers

c# - 如何使用保存对话框下载文件

c# - 使用计数进行分组 ASP.NET MVC

c# - 在 mvc 上获取站点 url

c# - 从列标题中的 TextBox 筛选 WPF DataGrid 值

python - Numpy-recarray,C#结构化数据

html - asp.net连接数据库读取数据

javascript - 如何使用自动回发进行计算以避免屏幕闪烁

asp.net - VirtualPathUtility.ToAbsolute() VS。网址内容()