views:

79

answers:

1

In order to generate clean markup, I often resort to using code similar to this:

<asp:Literal ID="ltItem" runat="server">
<li class="{0}"><a href="{1}">{2}</a></li></asp:Literal>

And in the codebehind:

...
lt.Text = string.Format(lt.Text,
    cssClass,
    item.Url,
    Server.HtmlEncode(item.Caption)
);

Some of the advantages are:

  • clean html markup, no ASP.Net WebForm id's etc
  • designer can do minor modifications in the aspx without developer intervention
  • code is precompiled (as opposed to use inline code or databind statements)

Disadvantages:

  • somewhat cryptic
  • fragile - when a parameter is removed in the markup, string.Format throws an exception

Therefore my question:

Is this a common way to generate clean markup? Are there better alternatives? Is the databinding syntax approach preferable?

A: 

It seems that you're fighting with your framework. ASP.NET web forms were designed to automatically resolve client-side ids and allow property-based UI customization that feels like Windows forms. These features often make a mess of the rendered HTML but the result is tolerated because of the perceived benefits.

If you don't perceive the benefits and find yourself fighting the ASP.NET web forms approach, consider another framework. There's no sense using a framework that doesn't share your values and goals.

If you want total control of your rendered HTML, consider ASP.NET MVC. Control of HTML output is one of its stated goals. In addition, it's designed to enforce separation of concerns.

If you're open to a non-Microsoft framework, there are many available including:

  • MonoRail - a framework inspired by Ruby on Rails
  • Maverick.NET - a .NET port of Java's Maverick framework
Corbin March