marapet
marapet

Reputation: 56516

Generating clean markup with Literal and string.Format

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:

Disadvantages:

Therefore my question:

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

Upvotes: 2

Views: 898

Answers (2)

Yohann Canu
Yohann Canu

Reputation: 167

Correct me if I am wrong but using MVC won't gives you precompiled code isn't it ? I do the same when using webforms and I had several issues with it.

Upvotes: 0

Corbin March
Corbin March

Reputation: 25734

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

Upvotes: 2

Related Questions