views:

76

answers:

3

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>
+4  A: 

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.

kbrimington
`<%: %>`, to be exact :)
Dan Dumitru
@Dan: Thanks. Corrected.
kbrimington
+2  A: 

It is bad if the data comes from an user input as your site will be vulnerable to XSS.

Darin Dimitrov
+1  A: 

No it's not a problem* because it will be scoped to your control. You don't have to worry about anything conflicting in your case but if you were writing out server controls with IDs you could run into problems.

How your using it, ok (*assuming you have cleaned the data before assigning it to your variable). Just keep in mind there are times when it can be an issue with duplication of IDs, controls, scripts, etc...

Edit: Before assigning it to your varible you could use HttpUtility.HtmlEncode or if you using ASP.NET 4 you can use the <%: syntax depending on what you are outputting. This fall under the same rules as doing it an aspx, it's ok but you just need to be careful. This is also how much of ASP.NET MVC is used. The views can be literred with <%= and <%: Obviously using any type of encoding on any HTML itself would not be useful.

Kelsey