Search code examples
c#asp.netdeclarative

Is it a Bad idea to use `<%=` in a WebControl


Recently I've started using <%= more often in my Web Controls. Typically I'll set String properties in the Code Behind and then spit them out onto the form.

Is this a bad idea?

eg.

Code Behind:

Properties:

public string TheTitle { get; set; }
public string TheBody { get; set; }
public ContentItem TheContent { get; set; }
public string ContentId { 
  get 
    { return "content" + (TheContent != null) ? TheContent.Id.ToSTring() : "0"; }
}

Page_Load:

TheTitle = TheContentItem.Title;
TheBody = TheContentItem.Body;

On Page:

<div id='<%= ContentID %>'>    

  <h2 class='title'><%= TheTitle ?? "No Title" %></h2>
  <p><%= TheBody %></p>

</div>

Solution

  • It is only a problem when the data is not validated.

    Using .NET 4's <%: TheBody %> syntax is an effective way to encode potentially-untrusted data. In earlier versions of the framework, you can use <%= HttpUtility.HtmlEncode(TheBody) %> to the same effect.