Razor - @Html.Raw() still encoding & in meta t

2019-06-17 01:50发布

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?

3条回答
Emotional °昔
2楼-- · 2019-06-17 02:11

You can do this in your _layout.cshtml:

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

This worked for me.

查看更多
别忘想泡老子
3楼-- · 2019-06-17 02:12

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)" />
查看更多
老娘就宠你
4楼-- · 2019-06-17 02:13

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;\"") />
查看更多
登录 后发表回答