ASP.Net 3.5: Specifying a control's HTML ID

妖精的绣舞 提交于 2019-12-10 10:42:32

问题


I have a control which is repeated several times in a page. I'd like each occurrence to have a unique ID which I will define (not the horrible ID asp.net attaches). The problem is that I will only know the ID in run time.

I'd like in the .aspx to write the following:

<uc8:MyControl ID="<%=THEID%>" runat="server" />

but I know it doesn't work. What's the right way to approach this?

Thanks a lot!


回答1:


You may add with code:

MyControl control = new MyControl();
control.ID == "myControl" + count.ToString();
ph.Controls.Add(control);

where ph - Placeholder or Panel control, count - some counter.




回答2:


Better to add the control from code behind, add a panel and then add controls to it.




回答3:


ASP.NET 4 has "predictable client ID's" http://www.asp.net/learn/aspnet-4-quick-hit-videos/video-8845.aspx




回答4:


Sadly, you're stuck with the .NET id at this time in ASP.NET 3.5. Unless you want to add the control programatically at run time, you can only Read the Id as it will appear on the client. You often have to do some client-side tricks to find the right control.

Once to make a form 508 compliant I had to analyze the pattern that .NET seemed to use to give id's to my nested controls and try to predict it. It seems to have worked for the past year; I keep my fingers crossed. Or, you can get the ClientID property at run time and write it to a hidden field, like so:

<input id='SpecialControlID' type='hidden' value='<%= SpecialControl.ClientID %>'>

Then you javascript can determine the ID. In short, there no good ways, only annoying hack ways. Easiest to add your controls at run-time.

Hope comes with VS2010, where you have options for improving this. You can change the settings for a control to use a specified ID, or to just simplify the algorithm .NET uses to determine the id, so that it is more predictable. Here's a good link.



来源:https://stackoverflow.com/questions/2132829/asp-net-3-5-specifying-a-controls-html-id

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