How to retain spaces in DropDownList - ASP.net MVC Razor views

11,703

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

Share:
11,703

Related videos on Youtube

JPReddy
Author by

JPReddy

Passionate to give solutions to real world problems using various technologies suitable for the solution. Has hands on with technologies like Install Shield, VB6, C, C++, VC++, PHP, Microsoft technologies since Dot net framework 2.0 (C#, ASP.net, VB.net).

Updated on September 05, 2020

Comments

  • JPReddy
    JPReddy over 3 years

    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
    JPReddy about 13 years
    That's brilliant. It worked like a charm. I wish I could give 100 upvote :)
  • Scott
    Scott almost 13 years
    Thanks for the great tip, I didn't know about this one.
  • Muflix
    Muflix almost 8 years
    Iam missing something, I add \xA0 as an output from database but in select list I don't see the space but "\xA0".. ?
  • Volkan Ceylan
    Volkan Ceylan almost 8 years
    If you are using CSHTML, it encodes strings by default, unlike ASPX. You might need to use @Html.Raw
  • yopez83
    yopez83 over 7 years
    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);