如何了解asp.net中回发的目标控件

本文关键字:控件 目标 net asp 何了解 了解 | 更新日期: 2023-09-27 18:18:59

首页

<html >
<head >
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnSubmit" runat="server" 
            OnClick="btnSubmit_Click"            
            Text="Submit to Second Page" />
</div>
</form>
</body>

btnSubmit_Click事件
Response.redirect("Page2.aspx");

在Page2的Page Load中,如何找到哪个按钮导致回发?

如何了解asp.net中回发的目标控件

btnSubmit_Click事件中可以传递查询字符串参数,在Page2中可以获取查询字符串参数。

Response.redirect("Page2.aspx?btnName=button1");

在Page2的加载事件。aspx页

protected void Page_Load(object sender, EventArgs e)
{
      string queryString = Request.QueryString["btnName"].ToString();
      //Here perform your action
}

Page_Load中,不可能找到哪个按钮引起PostBack。在第2页的point - view中,它是而不是,甚至不是Post。这是一个全新的要求。这就是回应。重定向,它指示客户端浏览器做一个新的请求。

如果你真的需要知道,你可以添加一个URL参数,并获得它作为一个查询字符串,如Pankaj Agarwal显示的是他的答案。

在注释后编辑:除了查询字符串,您可以在onClick:

中使用Session
Session["POST-CONTROL"] = "button2"

而在Page_Load中,您将其读为:

var postControl = Session["POST-CONTROL"] != null ? Session["POST-CONTROL"].toString() : "";

如果您确实需要帖子来自哪个按钮的信息,您将实现跨页面发布。这是一篇有例子的好文章。比起使用QueryString(实现起来可能快一些),我更喜欢这种方法。

有没有尝试过这个解决方案?这里:在回发,我如何检查哪个控件导致回发在Page_Init事件

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