Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Razor render SelectList without encoding

How can I get my select list to render without HTML coding

@{
    var noiceList = new SelectList(new[] { new {ID = "", Name = ""}, 
                                   new {ID = "y", Name = "Yes   after3Space"}, 
                 "ID", "Name"); 
 }
 @Html.DropDownList("noice", @noiceList )

rendered

..
<option value="y">Yes&amp;nbsp;&amp;nbsp;&amp;nbsp;3Space</option>
...

How do I get it to instead render

<option value="y">Yes&nbsp;&nbsp;&nbsp;after3Space</option>
like image 290
Joakim Avatar asked Sep 15 '11 10:09

Joakim


2 Answers

The easiest way to achieve this in C# is to use \xA0 instead of &nbsp; so you can avoid all that extra code.

Credit goes to this answer: How to retain spaces in DropDownList - ASP.net MVC Razor views

like image 182
BenC3 Avatar answered Nov 19 '22 03:11

BenC3


Unfortunately, this behavior is not built-in. The Html.DropDownList method (and most other HtmlHelper methods) always escapes all input text.

Workaround

There are workarounds, however. For example, you could create your own HtmlHelper method that allows unescaped HTML.

But if your needs are as simple as your example, here's a simple workaround:
Use a placeholder, such as |, and then replace it with &nbsp;, like this:

@{
    var noiceList = new SelectList(new[] { new {ID = "", Name = ""}, 
                                   new {ID = "y", Name = "Yes|||after3Space"}, 
                 "ID", "Name"); 
 }
 @Html.Raw(Html.DropDownList("noice", @noiceList).ToString().Replace("|", "&nbsp;"))

Note, you could also create a simple extension method to really reduce the amount of code required:

 public static HtmlString Replace(this HtmlString input, string findAll, string replaceWith) {
    return new HtmlString(input.ToString().Replace(findAll, replaceWith));
 }

This simplifies your Html code to:

 @Html.DropDownList("noice", @noiceList).Replace("|", "&nbsp;")
like image 34
Scott Rippey Avatar answered Nov 19 '22 03:11

Scott Rippey