Saturday, September 29, 2012

Dynamically add HTML markup to ASP.NET page

Sometimes you just might need to add dynamic HTML markup to your ASP.NET pages. I had to do the same thing and here I will show you how I did it.

First I created a div in my ASP.NET page like this:

<div id="myDiv" runat="server"></div>
The important things to note here are:
1. We need a name for the div, in this case "myDiv".
2. The attribute runat = "server". This attribute signifies that the control is a server control and the enclosed controls can be accessed by server scripts. If this attribute was missing, the server would have treated the line of code as a simple line of text.

Next thing to do we will write code in C# in the page load event. The full code looks like this:


protected void Page_Load(object sender, EventArgs e)
        {

            LiteralControl myList = new LiteralControl();
            System.Web.UI.Control myDiv = (System.Web.UI.Control)this.Page.FindControl("myDiv");

            StringBuilder sb = new StringBuilder(); //needs using System.Text on top of the page
            sb.Append("<ul>"); //the start of the list
            for (int i = 0; i < 4; i++)
            {
                sb.Append("<li>Item ");
                sb.Append(i.ToString());
                sb.Append("</li>");

            }

            sb.Append("</ul>"); //the end of the list

            myList.Text = sb.ToString();

            this.myDiv.Controls.Add(myList);

        }

So here we instantiate a LiteralControl whose text property will take the new HTML markup that we need on the page.

Then we search the page with the FindControl method of the Page that takes as parameter the name of the div where the new HTML will reside.

I created the HTML markup using a StringBuilder object. This class is very useful when working with strings because of the better memory management it has over the String class when concatenating.

The rest of the code is pretty clear.

No comments:

Post a Comment