简体   繁体   中英

Masterpage javascript causes an object reference error when asp.net control doesn't exist in the content page

So here's the deal: I have an asp.net control that is located on some content pages but not others. I would like to reference this asp.net control within a $(document).click event, the code for this is located in the master page. The code below is how I went about doing that; it searches the ContentPlaceHolder "body" for the control "dep_ddb" and retrieves its client id.

var dep_ddb = document.getElementById('<%= body.findcontrol("dep_ddb").ClientId %>');
var filterButton = document.getElementById('<%=body.findcontrol("filterButton").ClientId %>');

This works great when I am loading a page that includes the control. Unfortunately, when loading a page that doesn't use the control but uses the master page, I get an object reference error on that VB code: <%= blah blah %>.

I tried using a javascript if statement to detect if the content page doesn't include the control (simply by using the title to check if we are dealing with a content page I know won't include this control):

if (ttl.indexof('| Sign Up') == -1) {
    var dep_ddb = document.getElementById('<%= body.findcontrol("dep_ddb").ClientId %>');
    var filterButton = document.getElementById('<%=body.findcontrol("filterButton").ClientId %>');
};

. . . but it still caused the object reference error. I believe ASP is trying to compile the code included in the <% %> tags first, and is returning an error since it doesn't exist. Which would mean there is no javascript-based "if statement" I can use to omit this code when necessary.


So my question is this:

What method can be used to safely reference an asp.net control from the master page when the control exists in the content page, and omit the reference when it does not exist?


please both of the below links. may be you'll get some help:

Check if element exists in jQuery

Is there an "exists" function for jQuery?

one more thing, instead of using body.findcontrol("dep_ddb").ClientId try to give direct client id by getting it from page source. then i won't show you any server error.

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