ASP.Net: ClientID is not correct in the encoding of the user control

The following code does not work. The markup is in User Control, and I assume that why ClientID returns an invalid prefix for the TextBox identifier.

Markup:

<INPUT id="txtName" runat="server" maxlength="50" style="WIDTH:100px"> <INPUT type="button" value="Find Your Doctor" id="btnFind" runat="server" style="MARGIN-LEFT:10px;WIDTH:130px"> 

Code-Behind:

 btnFind.Attributes.Add("onClick",string.Format("DoctorLink ('{0}',document.getElementById('{1}').value,{2});", row["ZipCode"], txtName.ClientID)); 

Results in the browser:

 <input name="DoctorsMainArea1$ctl01$txtName" type="text" id="DoctorsMainArea1_ctl01_txtName" maxlength="50" style="WIDTH:100px" /> <input name="DoctorsMainArea1$ctl01$btnFind" type="button" id="DoctorsMainArea1_ctl01_btnFind" value="Find Your Doctor" style="MARGIN- LEFT:10px;WIDTH:130px" onClick="PrepareDoctorLink('90210', document.getElementById('DoctorsMainArea1_ctl00_txtName').value);" /> 

As you can see, the parameter for calling JavaScript is DoctorsMainArea1_ctl00_txtName , but the actual identifier of the input element is DoctorsMainArea1_ctl01_txtName .

Any idea how to fix this? Jquery I'm not interested in explaining what is happening (maybe there is another control on this page), but a more reliable way to solve the problem.

+6
c # clientid user-controls
source share
4 answers

You should try moving code that adds the onclick attribute to the button in the PreRender event (or OverPreRender override) on your page or user control. This should probably be ClientID privilege.

+4
source share

I don’t know which version of asp.net you are using, but in 4.0 you can declare ClientIDMode = "static" inside any server management and it will give you the exact identifier in the browser.

Example:

 <asp:Textbox id="txtName" runat="server" ClientIdMode="static"/> 

Others are predictable, inherited, and can be used with ClientIdRowsuffix.Can can be used at the page level and even on the main pages and even in the web.config file.

Example web.config file:

 <system.web> <Pages clientIDMode="predictable"/> other system web properties </system.web> 

Observed cobbler Craig Video on tekpub, you can also read about this in Rick's blog link text . This is pretty cool.

+5
source share

Fast decision:

 btnFind.Attributes.Add("onClick",string.Format("DoctorLink ('{0}',document.getElementById('{1}').value,{2});", row["ZipCode"], "DoctorsMainArea1_ctl01_" + txtName.ClientID)); 

This is because you have a content placeholder on your page.

0
source share

another solution: html tag:

 <input type="text" name="txtName" id="txtName" /> 

code-commit:

 string txtName_value = Request.Forms["txtName"]; 

and you can get the value

just use the html control.

0
source share

All Articles