Search code examples
asp.netinline-code

Cleaner way to write inline c# in .aspx page


For reasons that are probably not worth mentioning in this post, I have decided to stop using ASP.NET controls and simply use regular HTML controls for my .aspx pages. As such, to dynamically generate HTML, I use c# inline to the .aspx to do what I need to do.

For example: this .aspx snippet shows how I am dynamically creating a <select> element where the <option> elements are driven by looping through a generic list of objects.

<select name="s">
<option value="-9999">Select an entity...</option>
<% foreach (MyEntity e in this.MyEntities)
 {%>
<option <% if (MyEntityInScope.ID == e.ID)
 { %>selected<%} %> value="<%= e.ID %>">
<%= e.Name%></option>
<%} %>
</select>

Functionality-wise, I prefer this method of creating HTML (I feel more in control of how the HTML is generated vs ASP controls). However, syntactically (and visually), I think it's cumbersome (and ugly).

Is there a "better" way (another syntax) to dynamically generate HTML w/out resorting to using ASP.NET controls?


Solution

  • Why don't you put your logic into a method and call this method?

    string GetEntityList()
    {
    // ...
    }
    
    <select name="s">
    <option value="-9999">Select an entity...</option>
    <%=  GetEntityList() %>
    </select>