How to access HTML elements from server side code in an asp.net website

In this post I will demonstrate with a hands on example how HTML elements in an .aspx page can be processed exactly like standard ASP.Net server controls.

Basically how to make them accessible from server side code.

1) Launch Visual Studio 2010/2008/2005. (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose VB as the development language.

2) Add a new item in your site, a web form. Leave the default name.

3) Let's say that we want to change the background color of the page, thus access to the body element. We want to do that from our server side code.We must change the markup first

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

4) In the Page_Load event handling routine of the Default.aspx page, type

 MyBody.Attributes("bgcolor") = "teal"

 Run your site and see the background color of the page changing to teal.

5) If we wanted to have access to the head element, we follow the same path

<head runat="server" id ="theHead">

 In the Page_Load event handling routine of the Default.aspx page, type

  theHead.Title = "This is my first asp.net site"

 Run your site and see the new title.

6) What if we wanted to add a paragraph within our body element?

 In the Page_Load event handling routine of the Default.aspx page, type

  Dim myparagraph As HtmlGenericControl = New HtmlGenericControl("p")

  myparagraph.InnerText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
  et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat 
  non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  MyBody.Controls.Add(myparagraph)

 

 Run your site and see the new paragraph added to our site.

 7) Now we want to add programmatically an asp.net web server control inside a div element. Imagine that we want to add a Hyperlink web server control. Let's first add this div element inside our form element in the Default.aspx page

<div id = "mydiv" runat="server"/>    

In the Page_Load event handling routine of the Default.aspx page, type

        Dim mylink As HyperLink = New HyperLink

        mylink.Text = "DotNetStories Blog"

        mylink.NavigateUrl = "http://weblogs.asp.net/dotnetstories"

        mylink.Target = "_blank"

        mydiv.Controls.Add(mylink)

 

Run your application and see the new control added to our site.

That was a fairly easy post to follow.

Hope it helps!!!

No Comments