SoaresLuciano
SoaresLuciano

Reputation: 349

MVC2 Custom HTML Helper and <%: %> Syntax

Is there any way to use a custom html helper with the <%: %> syntax ?

I know that if i'm use the code below, it's ok, but it's seems not so elegant and secure.

<%= Html.MyHelper("Some Data")%>

I mean, use <%= %> is the best practices?

Upvotes: 3

Views: 990

Answers (2)

Esteban Araya
Esteban Araya

Reputation: 29664

Have your helper return an MvcHtmlString instead of a string. Also, please use <%: as much as possible.

Upvotes: 3

bobince
bobince

Reputation: 536529

HTML helpers create HTML, which is normally expected to be output raw with <%= %>. If you used <%: %> to HTML-escape the output of an HTML helper, you'll see the HTML source it produced on the page as text (eg literally <input name="foo" value="bar"> on-screen), which is probably not what you want.

It is up to the helper to HTML-escape any text content inside them, for safety. Yes, if you write a custom HTML helper and get it wrong—forgetting to HTML-encode strings your helper is putting in text content or attribute values in the output—you'll have security holes. You need to know what you're doing with escaping to write an HTML helper.

Microsoft, unfortunately, apparently don't, as the very first example in their tutorial completely fails:

return String.Format("<label for='{0}'>{1}</label>", target, text);

Whoops. Hope those ID and text strings didn't come from untrusted data!

[why are web tutorials always so lamentably terrible at escaping issues?]

Upvotes: 0

Related Questions