Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html control by ID that has hyphens?

I have a front end written in html that I am converting to asp, and many of the controls have names with "-" in them. This is causing crazy headaches, as there is no time to rename everything, and the ctrl-f and replace somehow breaks my css. Is there any way to access these controls in the code behind while they have the dashes? I have tried the code below.

//Can find when there is no dash in it, but that breaks the css after find/replace of full solution
HtmlGenericControl body = (HtmlGenericControl)this.Page.FindControl("page-list");
body.Attributes.Add("class", GlobalVariables.webAppSkin);

//I have also tried this, but logout stays null
WebControl logout = (WebControl)Page.FindControl("logout-link");

This is the html control:

<body id="page-list">
like image 253
KateMak Avatar asked Sep 18 '14 18:09

KateMak


3 Answers

Sorry, that's not gonna happen.

You cannot have an element with an id containing "-", and still be a runat="server" ASP.NET control.

Microsoft's docs about the control's IDs states:

http://msdn.microsoft.com/en-us/library/system.web.ui.control.id.aspx

Only combinations of alphanumeric characters and the underscore character ( _ ) are valid values for this property. Including spaces or other invalid characters will cause an ASP.NET page parser error.

If you tried adding runat="server" to the body tag you showed: <body id="page-list">, it would give you the following line in aspx.designer.cs:

protected global::System.Web.UI.HtmlControls.HtmlGenericControl page-list;

Which is obviously throwing an exception on C# syntax.

like image 57
LcSalazar Avatar answered Oct 19 '22 18:10

LcSalazar


<body id="page-list"> is not a HTML Control (i.e. an instance of (a subclass of) System.Web.UI.Control because it doesn't have the runat="server" attribute. If you were to add runat="server" then you would get a JIT compile-time error message informing you that "page-list" is not a valid identifier.

ASP.NET Web Forms 4.0 added the ClientIDMode attribute, however it doesn't allow you to set a completely custom ID attribute value. There's no easy solution for this without using <asp:Literal> or implementing your own control (or my preferred option: switching to ASP.NET MVC).

like image 26
Dai Avatar answered Oct 19 '22 17:10

Dai


You can access controls in code behind with their ID if you write runat="server". Here is the example for your case

<body runat="server" id="testID">

In code behind you can access it like this:

body.Attributes.Add("class", value);

like image 43
mybirthname Avatar answered Oct 19 '22 16:10

mybirthname