EF MVC RAZOR: how to decode HTML-encoded output lines of PartialView?

I am using EF4 + MVC 3 with Razor.

I have the following ActionResult that maps Dictionary<string,string> to a partial view.

ACTION

 public ActionResult combotest() { Dictionary<string, string> r = new Dictionary<string, string>(); r.Add("<> ''", "T"); ... return PartialView("_mypartial", r); } 

Now the special characters contained in the Model.Key values ​​are HTML Encoded, while I would like to use them as plain text. For example, <> '' appears as &lt;&gt; &#39;&#39; &lt;&gt; &#39;&#39; .

I tried converting them with WebUtility.HtmlDecode or Server.HtmlDecode without success:

PARTIAL VIEW (_mypartial):

 <select> <option value=''></option> @foreach (KeyValuePair<string,string> value in (Dictionary<string, string>)Model) { <option value="@WebUtility.HtmlDecode(value.Key)">@value.Value </option> } </select> 

could you help me? I would avoid using String.Replace if possible.

+6
source share
3 answers

To display text without code, you can use @Html.Raw(value.key)

+18
source

Larry

try the following:

  <select> <option value=''></option> @foreach (KeyValuePair<string,string> value in (Dictionary<string, string>)Model) { <option value="@Html.Raw(value.Key)">@value.Value </option> } </select> 

Html.Raw () returns an instance of HtmlString that wraps the original string. The Razor engine knows that it should not exit HtmlString instances, so the mapping matters as intended.

+2
source

Imagine not using 'string' in the first place, but rather an IHtmlString , for example using HtmlString .

For instance:

public ActionResult combotest() { Dictionary<IHtmlString, string> r = new Dictionary<IHtmlString, string>(); r.Add(new HtmlString("<> ''"), "T"); ... return PartialView("_mypartial", r); }

<select> <option value=''></option> @foreach (KeyValuePair<IHtmlString,string> value in (Dictionary<IHtmlString, string>)Model) { <option value="@value.Key">@value.Value </option> } </select>

Now you do not need to rely on an implicit security contract between the view (using Html.Raw) and the controller (providing reliable text). You provide valid, secure Html and mark it as such from the source.

0
source

Source: https://habr.com/ru/post/908611/


All Articles