3

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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?]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.