27

I'm binding my model in the following way in the view:

<%=Html.DropDownList("SelectedItem",new SelectList(Model.MyItems,"ItemId","ItemName")) %>

Issue is my item text is a formatted text with spaces in between words, as below.

#123  First          $234.00
#123  AnotherItem    $234.00
#123  Second         $234.00

I want to retain the spaces in this item text even after they are added to DropDownList. But unfortunately my DropDownList shows them without spaces as below:

#123 First $234.00
#123 AnotherItem $234.00
#123 Second $234.00

When I view the source of the page those spaces are intact but in display it is not. I've tried to add '&nbsp;' instead of spaces but SelectList (MVC framework class) internal method is using HtmlEncode before adding them as items in the dropdownlist.

Is there any way I can achieve this?

JPReddy
  • 63,233
  • 16
  • 64
  • 93

1 Answers1

64

nbsp in html corresponds to "\xA0" as a C# string, so use this instead of spaces, when HTML encoded it will produce nbsp

Volkan Ceylan
  • 1,486
  • 13
  • 15
  • That's brilliant. It worked like a charm. I wish I could give 100 upvote :) – JPReddy Apr 29 '11 at 08:54
  • Iam missing something, I add \xA0 as an output from database but in select list I don't see the space but "\xA0".. ? – Muflix May 12 '16 at 13:10
  • If you are using CSHTML, it encodes strings by default, unlike ASPX. You might need to use @Html.Raw – Volkan Ceylan May 21 '16 at 06:52
  • I am running into the same issue and I haven't been able to get it to work. My page is CSHTML, and the way I concatenate is through string.Format({0,-15} | {1}, text1, text2); – dotnetspark Oct 25 '16 at 19:05