我的 ASP.Net TextBox 有一个自动生成的名称,这意味着我无法在客户端脚本中使用它...如何使用服务器和客户端代码?
我有一个需要访问 TextBox 的脚本,但是 ASP.NET 生成了一些疯狂的名称:ctl00$ContentPlaceHolder1$txtEmpFirstName
...客户端脚本使得无法知道如何访问此控件。
我们如何解决这个问题?我还需要能够在按下按钮时从服务器端代码访问文本,如果这有什么不同吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在客户端代码中访问文本框的
ClientID
属性。You can access the TextBox's
ClientID
property in your client side code.我们处理这种情况的方法是在服务器端为每个需要在客户端访问的控件编写一个javascript变量。
例如:
这在以下几种情况下是必要的:
1) 如果您的 javascript 与代码页是分开的
2) 如果您正在处理第三方控件,这些控件需要稍微不同的方法来识别客户端的控件(我们使用某些控件,其中 ClientID 中的下划线必须替换为 x 或完全删除)。是的,您可以在内联脚本中执行此操作,但您必须记住每次访问控件时都执行此操作。在服务器端执行此操作允许您创建通用的、特定于控件类型的方法,这些方法每次都可以正确地为您生成适当的客户端 ID。
3) 如果您在页面中动态生成了控件,而其 clientid 在设计时可能未知。
这些只是我们遇到过的场景,需要将 id 作为代码隐藏中的 js 变量生成。我知道还有更多。
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:
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.