开发者

ASP.NET 4 changes with automatic names of controls

开发者 https://www.devze.com 2022-12-26 10:26 出处:网络
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:

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


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.


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


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 %>');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号