2

如何获取PostBack在 asp.net 中导致的控件的 ID。我用

document.getElementById("__EVENTTARGET")

但它只给出了objectHtmlInputElement一个不完整的 ID。我怎样才能只在 javascript 中而不是在后面的代码中得到这个。我希望在回发后专注于该元素。请帮忙..

4

2 回答 2

4

您可以使用本博客中提到的这个函数来获取回发控件的 id,将此 id 存储在 hiddenfield 中并使用 JS 从 hiddenfield 中获取该 id

 protected void Page_Load(object sender, EventArgs e)
    {    
        if (Page.IsPostBack)
           HiddenField1.Value = getPostBackControlName();
    } 

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;
}
于 2012-12-27T12:42:29.020 回答
1

采用document.getElementById('__EVENTTARGET').value

于 2014-01-28T19:02:16.823 回答