1

I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

@Html.MyMenu()

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

<div id="menucontainer">

                &lt;a href=&quot;/Anuncio/Electronics&quot;&gt;Electronics&lt;/a&gt;&lt;a href=&quot;/Anuncio/Clothes&quot;&gt;Clothes&lt;/a&gt;&lt;a href=&quot;/Anuncio/Domestic&quot;&gt;Domestic&lt;/a&gt;&lt;a href=&quot;/Anuncio/Garden&quot;&gt;Garden&lt;/a&gt;

            </div>

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

<%: this is rendered, right? %>

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Please let me know if you need to see the code in the View. Thanks! –  Dec 14 '10 at 13:09

4 Answers4

2

Razor escapes HTML by default.

To avoid that, please do something like this:

Writing/outputting HTML strings unescaped

Community
  • 1
  • 1
rsenna
  • 11,775
  • 1
  • 54
  • 60
  • Thanks, this helped me solve my problem. Here's my solution: @(new HtmlString(@Html.MyMenu())) –  Dec 14 '10 at 13:19
  • But you could also make `Html.MyMenu()` return a `HtmlString`! I guess it would be better... Unless you need it to return a regular string (for reusing it somewhere else, for instance). – rsenna Dec 14 '10 at 13:22
1

In RC2 a new method called @HTml.Raw should to this.

Or you can change MyMenu to return HtmlString or MvcString rather than just string.

Zote
  • 5,343
  • 5
  • 41
  • 43
  • I can't find this method on MSDN and Google returns no results. Can you share a link? –  Dec 14 '10 at 13:22
  • @sergio sure! http://stackoverflow.com/questions/4281424/asp-net-mvc-razor-output-html-string-non-escaped/4282073#4282073 – Zote Dec 15 '10 at 16:16
0

well your extension method should be returning an MvcHtmlString in order to properly display on your page using the <%: %> If it returns a string, all angle brackets and other html special characters will be html-encoded.

Peter Perháč
  • 20,434
  • 21
  • 120
  • 152
  • I only mentioned the brackets to illustrate what I'm trying to accomplish. You can't use the brackets of MVC2 on the Razor engine. –  Dec 14 '10 at 13:16
0

RC2 supports @Html.Raw() to output raw HTML

From Scott Guthrie's RC2 anouncement

With RC2 we are adding a Html.Raw() helper method that you can use to explicitly indicate that you do not want to HTML encode your output, and instead want to render the content “as-is”

David Glenn
  • 24,412
  • 19
  • 74
  • 94