Reputation: 573
I am using EF4 + MVC 3 with Razor.
I have the following ActionResult
, which renders a Dictionary<string,string>
into a partial view.
ACTION
public ActionResult combotest()
{
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("<> ''", "T");
...
return PartialView("_mypartial", r);
}
Now, special chars contained into the Model.Key
values are HTML Encoded, while I'd like to use them as plain text. For example <> ''
is rendered as <> ''
.
I tried to convert 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 to use String.Replace
, if possible.
Upvotes: 7
Views: 17834
Reputation: 10610
Consider not using 'string' in the first place, but rather IHtmlString
, for example with HtmlString
.
For example:
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 don't have to rely on an implicit security contract between the view (using Html.Raw) and the controller (providing text that is hopefully safe). You're providing valid, safe Html and marking it as such from the source.
Upvotes: 0
Reputation: 22485
Larry,
try this:
<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 HtmlString instance that wraps the original string. The Razor engine knows not to escape HtmlString instances, thus display is as intended.
Upvotes: 2
Reputation: 3062
To display text unencoded you can use @Html.Raw(value.key)
Upvotes: 22