My ASP.Net TextBox has an auto-generated name, which means I can't use it in client side scripts… how do you use both server and client side code? [duplicate]

StackOverflow https://stackoverflow.com/questions/8248629

Question

Possible Duplicate:
Need the clientId of a textbox inside a content control using javascript

I have a script that needs to access a TextBox, but ASP.NET generates some crazy names: ctl00$ContentPlaceHolder1$txtEmpFirstName ... client side scripting makes it impossible to know what to do to access this control.

How do we get around this? I also need to be able to access the text from server-side code when a button is pressed if that makes a difference?

Était-ce utile?

La solution

You can access the TextBox's ClientID property in your client side code.

<%= TextBox.ClientID %>

Autres conseils

The way that we handle this situation is to write a javascript variable on the server side for each control that needs to be accessed in the client side.

For example:

string sScript = "var m_stxtEmpFirstName = '" + txtEmpFirstName.ClientID + "'";

ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", sScript, true);

This is necessary in a couple of situations:

1) If your javascript is separate from your code page

2) If you are dealing with third-party controls that require a slightly different method of identifying the controls on the client side (we work with some controls in which in underscores in the ClientID have to be replaced with x or removed altogether). Yes, you could do this in the inline script, but you'd have to remember to do it every time to accessed the control. Doing this on the server side allows you to create generic, control type-specific methods that can generate the appropriate client id for you correctly every time.

3) If you have dynamically generated controls in the page for which the clientid may not be known at design time.

These are just the scenarios off the top of my head that we have encountered that required the ids to be generated as js variables in codebehind. I know that there are many more.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top