How to retain spaces in DropDownList - ASP.net MVC Razor views
nbsp in html corresponds to "\xA0" as a C# string, so use this instead of spaces, when HTML encoded it will produce nbsp
Related videos on Youtube
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, 2020Comments
-
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 '
' 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 about 13 yearsThat's brilliant. It worked like a charm. I wish I could give 100 upvote :)
-
Scott almost 13 yearsThanks for the great tip, I didn't know about this one.
-
Muflix almost 8 yearsIam missing something, I add \xA0 as an output from database but in select list I don't see the space but "\xA0".. ?
-
Volkan Ceylan almost 8 yearsIf you are using CSHTML, it encodes strings by default, unlike ASPX. You might need to use @Html.Raw
-
yopez83 over 7 yearsI 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);