Dynamically Generate HTML in ASP.NET (in Code-Behind)

I do not enjoy working with ASP.NET Form Controls. I prefer to use regular HTML controls and, then, use C# to dynamically generate the HTML that I want to send to the browser.

In a previous post I discussed how to create a <select> element with dynamically generated <option> elements. Although the example in that post works fine, it is a bit cumbersome to write and very ugly to look at.

Here, I propose a different way for generating the same HTML.

In the code-behind of my ASP.NET application, I have a method that will return a string that was generated by looping through a list of entities where each entity is wrapped with HTML <option> element syntax:

protected string GetControllerOptions()
string options = "<option value='-9999'>Select a controller...";
string selectedAttribute = string.Empty;
foreach (Controller c in GetControllers())
selectedAttribute = this.ControllerInScope.ControllerId == c.ControllerId ? "selected" : string.Empty;
options += "<option " + selectedAttribute + " value='" + c.ControllerId.ToString() + "'>" + c.ControllerName;

In the .aspx source page I have the following:

<select onchange="GoToUrl('?conscopeid=' + document.getElementById('selControllerScope_ControllerId').value);"
<%= this.GetControllerOptions() %>

The reason why I prefer this method of generating HTML is it moves the “work” of if/then/else statements to the code-behind (which is where it should be) and makes for a cleaner HTML page. In other words,

<%= this.GetControllerOptions() %>

is much nicer to write (and look at) then ….

<option value="-9999">Select a controller...</option>
<% foreach (Controller c in this.UserControllers)
<option <% if (ControllerInScope.ControllerId == c.ControllerId)
 { %>selected<%} %> value="<%= c.ControllerId %>">
<%= c.ControllerName%></option>
<%} %>

… don’t you think?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s