Thursday, 23 October 2008

Referencing HTML tags from code-behind

In many instance of developing performant ASP.NET applications, you will require the need to reference standard HTML tags from code-behind. You may notice that if you associate an ID to a HTML tag, you still cannot control this from code behind.

The understanding behind this is quite simple. HTML tags are client-side controls, not server-side. Therefore, they are purely rendered by the users browser and no server processing is executed upon them. The code-behind view details events for server-side components only.

Therefore it becomes obvious that we need to make our tag a server-side component. To do this, we follow these steps:

1. Alter your HTML tag by giving it an ID (so we can reference it from the code-behind) and tell it to run at the server. I.e.

2. Browse the object library to find out what library this HTML tag belongs to. A 'div' tag for example would be a 'HtmlGenericControl' object. We therefore define this publicly in our code behind file (using the ID as before). I.e. public HtmlGenericControl test;

3. We can then use the methods of the 'HtmlGenericControl' object to control the DIV tag. A popular method would be: display.InnerHtml = "Hello World"


No comments: