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:
- 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 alte开发者_高级运维rnatives? Is the databinding syntax approach preferable?
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
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.
精彩评论