简体   繁体   中英

From Master page - How to find the clientID of item in Child page which may or may not be there

I have the following setup:

  1. Master Page
  2. Child Page
  3. External Javascript file

In the Child page I sometimes can have a hidden control called 'hiddenFoo'. In the js file I have a variable called 'hFoo' which should contain the ClientID of hiddenFoo .

Now I know I can add hFoo = "<%=hiddenFoo.ClientID %>"; to each Child page but I am wondering if it is possible to do that within the Master page (taking note that hiddenFoo is not on every page).

** edit with answer **
1. In my master page javascript I checked if 'hiddenFoo' existed within my content.
2. If this returned not blank I called the code behind to return the ClientID.

<script type="text/javascript">  
    if ('<%=MainContent.FindControl("hiddenFoo") %>' != '') {  
        hiddenFooID = "<%=GetHiddenFooClientID %>";  
    }  
</script> 

protected string GetHiddenFooClientID   
{  
    get {   
        Control hiddenFoo = MainContent.FindControl("hiddenFoo");  
        if (hiddenFoo != null) {  
            return hiddenFoo.ClientID;  
        }  
        return " ";  
    }  
}  

You can implement the recursive version of the FindControl method, or pick one already available, like this one . After that in the master page code behind you can create a property like this:

protected string HiddenFooClientID
{
    get
    {
        Control hiddenFoo = FindControlRecursive("hiddenFoo");
        if (hiddenFoo != null)
        {
            return hiddenFoo.ClientID;
        }

        return String.Empty;
    }
}

and call it on the markup:

hFoo = "<%=HiddenFooClientID %>";

You can use a URL parameter to pass a variable from page to page. You will still need to declare the variable on every child page.

var hFoo = "<%=Request.QueryString["ClientID") %>";

From the master page, the link to the child page should be like this: "childPage.aspx?ClientID=XXX"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM