Search code examples
asp.net-mvcasp.net-mvc-4razorrazor-2

PartialView to create a select box: How to Html.Encode Output?


I have this partial view:

@model Dictionary<int, string>

<select style="height: 17px;">
  <option value=''></option>
  @foreach (KeyValuePair<int, string> value in Model)
  {
    <option value='@Html.Encode(value.Key.ToString())'>
      @Html.Encode(value.Value)
    </option>
  }
</select>


Works fine, but if there are e.g. German umlauts in the value it is displayed wrong: enter image description here

So instead of ö there is &#246;.

If I use @value.Value instead of @Html.Encode(value.Value) it works but I want to Html.Encode the values from a database because of security reasons.


Solution

  • You don't need to manually Html.Encode because Razor secure by this manner. This means that Razor HTML encodes every string what you write to the output with the @ sing.

    So you can just safely write @value.Value.

    By the way the effect what you are seeing is the case of the double encoding because you first encode for text with Html.Encode and then Razor encodes the already encoded text for the second time when you write it out with @Html.Encode(value.Value).