8

When I use @Html.Raw(mystring) normal it renders properly example:

@{ ViewBag.Title = "My Site®"; }
<title>@Html.Raw(ViewBag.Title)</title>

Will properly render <title>My Site&reg;</title> but when I use it in an attribute:

<meta name="description" content="@Html.Raw(ViewBag.Title)" />

It renders <meta name="description" content="My Site&amp;reg;" /> which is not correct because then it will not render the registered mark.

How do you correct this behavior?

ddilsaver
  • 990
  • 3
  • 10
  • 19
  • Duplicate: http://stackoverflow.com/questions/11963453/why-is-html-raw-escaping-ampersand-in-anchor-tag-in-asp-net-mvc-4 and http://stackoverflow.com/questions/12321616/why-is-mvc-4-razor-escaping-ampersand-when-using-html-raw-in-a-title-attribute – Justin Helgerson Feb 15 '13 at 19:04
  • @Ek0nomik It's not really a duplicate because no one resolved that question. They're suggestion was load the whole tag into the string and that is stupid do to on every page. – ddilsaver Feb 15 '13 at 19:09
  • You can just include the attribute name in the parameter to `.Raw` as shown in the second question linked above. You're going to have to do a work around as this is a bug: http://aspnetwebstack.codeplex.com/workitem/393. – Justin Helgerson Feb 15 '13 at 19:14
  • @Ek0nomik I didn't see the second question when I first looked. It had the better solution. You can post it as an answer if you want. Otherwise I'm going to post my code solution so it's available. – ddilsaver Feb 15 '13 at 19:22
  • No worries. I added an answer. Best of luck! – Justin Helgerson Feb 15 '13 at 19:25

3 Answers3

8

As patridge pointed out in his answer you can just include the attribute markup in the parameter to .Raw.

In your case that would result in something similar to the following:

<meta name="description" @Html.Raw("content=\"My Site&amp;reg;\"") />
Community
  • 1
  • 1
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
0

You can do this in your _layout.cshtml:

<title>@{var title = new HtmlString(ViewBag.Title);}@title</title>

This worked for me.

0

I think it's the tip-top solution:

@{ ViewBag.Title = "My Site&reg;"; }
<title>@Html.Raw(ViewBag.Title)</title>
<meta name="description" content="@HttpUtility.HtmlDecode(ViewBag.Title)" />
Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108