I can't stand it when people use Label controls to populate their ASP.NET pages with markup, like this:
Label1.Text = "<a href=\"javascript:void(0)\">Link</a>";
Anytime you see someone using StringBuilders to generate lines upon lines of HTML, you just know that
it's procedural, not object-oriented code and (b) it's going to be unmaintainable spaghetti code after they're done. They are PHP/ASP programmers in ASP.NET programmers' clothing.
Use the intrinsic HtmlControls and WebControls to generate your markup:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="javascript:void(0)" Text="Link" />
or
<a id="Anchor1" runat="server" href="javascript:void(0)">Link</a>
A suitable but more advanced alternative would be to learn how to write your own server-side controls. Here is a crude example, but the gist of the suggestion here is that you want to make reusable code that
has a semantically useful presence in your ASP.NET markup and (b) provides some sort of Visual Studio/Expression Studio design-time experience.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
namespace MyControlLib
{
[DefaultProperty("Text")]
public class MyAnchor : System.Web.UI.Control
{
public MyAnchor()
: base()
{
Href = "javascript:void(0)";
Text = "Link";
}
[DefaultValue("javascript:void(0)")]
public string Href
{
get { return (string)ViewState["href"] ?? string.Empty; }
set { ViewState["href"] = value; }
}
[DefaultValue("Link")]
public string Text
{
get { return (string)ViewState["Text"] ?? string.Empty; }
set { ViewState["Text"] = value; }
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
bool inDebugMode = HttpContext.Current == null;
writer.WriteBeginTag("A");
writer.WriteAttribute("href", Href, true);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(string.IsNullOrEmpty(Text) && inDebugMode) ? string.Format("[{0}]", ID) : Text);
writer.WriteEndTag("A");
}
}
}
In the markup, it would look like this:
<%@ Register Assembly="MyControlLib" Namespace="MyControlLib" TagPrefix="cc" %>
<cc:MyAnchor ID="MyAnchor1" runat="server" />
Using StringBuilders is the semantic equivalent of using document.writeln()-style JavaScript to build Web pages. It's an unreadable, unmaintainable mess where your ideas are expressed with crude, long-winded, ill-suited metaphors rather than clear, concise language.
UserControls are another great way to develop your own custom server-side controls without having to "live in the code-behind."