【问题标题】:How do I find out which button triggered the postback?如何找出哪个按钮触发了回发?
【发布时间】:2013-10-29 11:09:56
【问题描述】:

在 asp.net (c#) 中如何找出哪个 asp:button 触发了回发?

我将它用于动态控件,并希望在页面加载时为不同的按钮执行不同的过程。我曾尝试查看 __EVENTARGUMENTS 等,但它们没有用。

我想做这样的事情:

页面加载 案子: 单击按钮 1 //做点什么 按钮 2 被点击 //做点什么

【问题讨论】:

  • 为什么不直接使用按钮点击事件?
  • 好的。一种替代方法是当您单击在 javascript 端的隐藏字段中设置唯一值的任何按钮时。然后在加载时检查该唯一值并根据您的要求进行操作。
  • 你也可以在 ViewState 中存储一些东西,但我认为@Grant 在这里有正确的想法。我的很多页面都是 if(IsPostback) 什么都不做,否则加载初始页面,并且有一个真正的 main 方法,许多但不是全部的事件方法调用。

标签: c# asp.net visual-studio-2012 webforms


【解决方案1】:

使用下面的代码。

  public static string GetPostBackControlId(this Page page)
        {
            if (!page.IsPostBack)
                return string.Empty;

            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 controlName = page.Request.Params["__EVENTTARGET"];
            if (!String.IsNullOrEmpty(controlName))
            {
                control = page.FindControl(controlName);
            }
            else
            {
                // if __EVENTTARGET is null, the control is a button type and we need to
                // iterate over the form collection to find it

                // ReSharper disable TooWideLocalVariableScope
                string controlId;
                Control foundControl;
                // ReSharper restore TooWideLocalVariableScope

                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"))
                    {
                        controlId = ctl.Substring(0, ctl.Length - 2);
                        foundControl = page.FindControl(controlId);
                    }
                    else
                    {
                        foundControl = page.FindControl(ctl);
                    }

                    if (!(foundControl is Button || foundControl is ImageButton)) continue;

                    control = foundControl;
                    break;
                }
            }

            return control == null ? String.Empty : control.ID;
        }

调用这个函数:

我已将上述函数包含在静态类 UtilityClass 中。

String postBackControlId = UtilityClass.GetPostBackControlId(this);

代码已引用自 Mahesh's Blog

【讨论】:

  • 如果您从某处获取代码,请务必注明来源参考
  • 没关系..有时我们都忘记了
  • 他们的问题在于该代码中的两个返回错误是错误 2 由于 'Portal.NewAjaxTabTest.Page_Load(object, System.EventArgs)' 返回 void,return 关键字后面不能跟对象表达式
  • 我不认为它会抛出任何错误,因为我已经使用了很多年了。 return 语句也有效。你能告诉我你是如何调用这个函数的吗?希望您使用类名访问它,因为它是静态的。
  • 我也包含了函数调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 2011-12-27
  • 2011-04-16
  • 1970-01-01
  • 2011-04-02
  • 2011-11-22
相关资源
最近更新 更多