Is HTML.raw()
specific to MVC? On what scenarios we have to use it?
Can you please explain with an example.
回答1
Text output will generally be HTML encoded.
Using Html.Raw allows you to output text containing html elements to the client, and have them still be rendered as such.
Should be used with caution, as it exposes you to cross site scripting vulnerabilities.
回答2
HtmlHelper.Raw MSDN
Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.
Because encoded characters are HTML, and the Raw version of that string is the encoded one.
Html.Raw renders what it is given without doing any html encoding, so with ViewBag.div = "<div> Hello </div>";
:
@Html.Raw(ViewBag.div);
Renders
<div> Hello </div>
However, when you have encoded characters in there, such as ViewBag.Something = ">";
the raw version of that is >
. To get back to actual html you need to Html.Raw(HttpUtility.HtmlDecode(EncodedContent));
as you‘ve said.
If Html.Raw did do the decoding then it would be confusing, and we would need something that didn‘t do it. ;-)
The HTML markup without encoding.
In the controller use
model.MyLink = HttpUtility.HtmlDecode(url);
then in the view use
@Html.Raw(Model.MyLink)
The first converts it to use
You are close you want to use @Html.Raw(str)
@Html.Encode
takes strings and ensures that all the special characters are handled properly. These include characters like spaces.
You should HTML encode as you print in your view (using @Model
).
Do not encode or decode anywhere else; do not store encoded content in your database.