Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I count on ctl00_PagePlaceHolder_myId staying the same?

I need to push something into my ASP.NET web form page from a Silverlight control.

I set the ID of my text box and, as is it's want, ASP.NET "helpfully" adds on the ctl...blah_blah stuff. Can I assume this will always be the same gumpf it puts on the beginning of my id?

Kindness,

Dan

EDIT: Thanks for the responses guys.

Using the HtmlPage.Document from my Silverlight control, I used Doug's solution as such ...

var spec = HtmlPage
            .Document
            .GetElementsByTagName("input")
            .FirstOrDefault(so => ((HtmlElement)so).CssClass == "spec");
like image 916
Daniel Elliott Avatar asked Feb 27 '23 18:02

Daniel Elliott


2 Answers

No, it could easily change if you ever add another control in front of it, or nest it in another control. Additionally, the id is different depending on the browser. In some browsers .NET splits with _ other browsers use $. I haven't worked with Silverlight, but can you find an element with a certain class? You could apply a class name to your element and ASP.NET won't edit it at all.

like image 192
Doug Neiner Avatar answered Mar 05 '23 12:03

Doug Neiner


No. In some circumstances it can be rendered differently and changes elsewhere in the page might change this control. The correct way to handle this is to reference the control's .ClientID property.


Update

This is how I normally handle client ids:

<head runat="server">
   ...
   <script language="javascript">
   var ControlIDs = {
       SomeControl = <%="'" + SomeControl.ClientID%>',
       OtherControl = <%="'" + OtherControl.ClientID%>'
   };
   </script>

   ... other script references here ...
</head>

I put the script first in the head element so that it's accessible to other script files; this way I don't need to pass javascript files through the asp.net processor and I only have to write out each client id once. There's no need to worry about escaping anything, because the ' and \ characters will never be part of a rendered client ids. The reason for the controlIDs object is to avoid naming collisions with other scripts, and the reason for concatenating the "'" at the front in server code is that asp.net won't see the <% otherwise.

Again: this is what I normally do, but for some simple pages it might be overkill.

like image 31
Joel Coehoorn Avatar answered Mar 05 '23 10:03

Joel Coehoorn