c# - textbox or any control id keep on changing, why? - Stack Overflow

admin2025-04-19  0

For my textbox, the following id generated on my local.

ctl00_ContentPlaceHolder1_ucLogin1_txtUserName

When I hosted on IIS, the following id got generated.

ContentPlaceHolder1_ucLogin1_txtUserName

How can I get the textbox id? Don't reply answer as use ClientID, cos now I'm using external javascript file. It wont support ClientID.

For my textbox, the following id generated on my local.

ctl00_ContentPlaceHolder1_ucLogin1_txtUserName

When I hosted on IIS, the following id got generated.

ContentPlaceHolder1_ucLogin1_txtUserName

How can I get the textbox id? Don't reply answer as use ClientID, cos now I'm using external javascript file. It wont support ClientID.

Share edited Jul 22, 2011 at 8:44 Alex R. 4,7384 gold badges32 silver badges40 bronze badges asked Jul 22, 2011 at 8:36 negaboysnegaboys 624 bronze badges 2
  • You might want to take a look at this question. – Dan Abramov Commented Jul 22, 2011 at 8:41
  • I don't know about others, but your question is not clear to me. Please provide more info – Mo Valipour Commented Jul 22, 2011 at 8:53
Add a ment  | 

6 Answers 6

Reset to default 7

If you're using ASP.NET 4.0 you can set ClientIDMode of the textbox to Static and its id always will be the same.

Example:

<asp:TextBox ID="txtUserName" runat="server" ClientIDMode="Static" />

you could use that jquery

var clientId =$('input[id*="txtUserName"]').attr("id");

remember; 'input[id*="txtUserName"]' select all input element which is id has got "txtUserName".

You have to use ClientID, but what you can do is use a small bit of javascript on your page to set a variable to the passed ClientID for use with your external script.

Failing that if your using version 4 of the .Net Framework you can set ClientIDMode to Static so you have control over the ID Generation. See http://weblogs.asp/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx

There're a lot of ways to solve that, but one that'd be quick to implement is just add an unique CSS class to this TextBox.

That'd allow you to retrieve this TextBox in client-side by its CSS class by using some JavaScript client framework like jQuery:

$("input.MyTextBoxCssClass")

Another approach, if you are in ASP.NET 4.0 is the one suggested by bniwredyc in his answer.

You have two options:

If you're targetting to ASP.NET 4.0 you can use set ID explicitly. Here are examples of how it is done.

Another option would be to pass the TextBox ID to your javascript function as a parameter and use the "ClientID" method when calling the javascript function. Here is a similiar question.

You should select the textbox without using its ID. Try adding a class to the textbox and selecting that:

<asp:TextBox ID="txtUserName" runat="server" CssClass="txtUserNameClass"/>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745074813a283504.html

最新回复(0)