ASP.NET 4 changes with automatic names of controls

泄露秘密 提交于 2019-12-23 03:12:50

问题


I just updated an app from .NET 2.0 to .NET 4.0 and I have noticed the following.

For example I have the following control:

<input type="hidden" name="ctl00$cphMain$hfdFueraHorarioOficinaConfirmado" 
 id="cphMain_hfdFueraHorarioOficinaConfirmado" value="False" />

and then in javascript I did this before:

 var hfdFueraHorarioOficinaConfirmado=document.getElementById('ctl00_cphMain_hfdFueraHorarioOficinaConfirmado');

but after checking the id within the html source once it renders and also doing some debugging with firebug etc it has changed from:

ctl00_cphMain_hfdFueraHorarioOficinaConfirmado

to:

cphMain_hfdFueraHorarioOficinaConfirmado

Can anyone explain why? Should I basically do a search and replace and remove the ctl00?

Obviously the javascript line with the ctl00_ in front returns null because it doesn't exist, but removing this returns the object.

Any help or ideas really appreciated


回答1:


There have been some changes, which look like for the better, but Microsoft have created a compatibility flag you can set to retain backwards compatibility with .NET 3.5 - see this article.

You can set the ClientIDMode property to AutoID in your web.config file to retain the previous behaviour, and override it on individual controls gradually as you start to make changes throughout your code.




回答2:


In your script files, you should look at always using the ClientID that you get on the server side (and output as a script variable on the page).

I think that there are also ways of setting how the control naming is done in 4.0, you might be able to pick a setting that solves your problem:

http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx




回答3:


ASP.Net automatically generates client IDs for server-side controls.

As you've discovered, you must not rely on these automatically generated names staying the same.

In ASP.Net 4.0, you can set the ClientIDMode property to Static. Your ID will then be used untouched as the client-side ID.

In all versions of ASP.Net, you should use the ClientID property instead of hard-coding the ID.

For example: (In the ASPX page)

var hfdFueraHorarioOficinaConfirmado = 
    document.getElementById('<%= hfdFueraHorarioOficinaConfirmado.ClientID %>');


来源:https://stackoverflow.com/questions/2629770/asp-net-4-changes-with-automatic-names-of-controls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!