asp.net-mvcindentationhtml.dropdownlistfor

  changes to &nbsp in asp.net mvc html.dropdownlist


I want to show items with indention in html.dropdownlist

this is code in controller

IEnumerable<ViewModels.testvm> test = db.Database.SqlQuery<ViewModels.testvm>(@"WITH tree (id, parentid, level, title, rn) as 
(
   some code
)
***********SELECT id,REPLICATE('&nbsp;',level) + title as title
FROM tree
order by RN");
ViewBag.ParentID = new SelectList(test, "ID", "Title");

as you can see I add &nbsp to dropdown items in replecate

but the problem is &nbsp shows in dropdown.

this is view > source result:

 <select class="form-control" id="ParentID" name="ParentID"><option 

value="10">Menu1</option>
<option value="11">&amp;nbsp;Sub1</option>
<option value="14">&amp;nbsp;Submenu1</option>
<option value="12">Menu2</option>
<option value="16">&amp;nbsp;sub2</option>
<option value="13">Menu3</option>
<option value="15">&amp;nbsp;sub3</option>
<option value="17">&amp;nbsp;&amp;nbsp;sub sub</option>
<option value="22">&amp;nbsp;&amp;nbsp;&amp;nbsp;sub3 sub sub</option>
<option value="19">menu4</option>
<option value="20">&amp;nbsp;sub4</option>
<option value="21">menu5</option>
</select>

as you can see &nbsp; converted to &amp;nbsp;

I tried "\xA0" instead of &nbsp but it shows in dropdown too!

I think html.raw can solve this, but I don't know how can I use it with html.dropdownlist.

this is view

<div class="col-md-10">

@Html.DropDownList( "ParentID", null, htmlAttributes: new { @class = "form-
control" })

</div>

any Idea?


Edit

by changing view like this the problem solved: I tried this after checked a post as answer

   <select class="form-control" id="ParentID" name="ParentID">
        <option value="0">First Level</option>
        @foreach (var item in ViewBag.ParentID)
        {
            <option value="@item.Value">@Html.Raw(@item.Text)</option>
        }
    </select>

Solution

  • You can manually create the dropdown list assuming you place your collection in a ViewModel member called ParentIDs:

    The View:

    @if (Model.ParentIDs.Any())
    {
        <select class="form-control" id="ParentID" name="ParentID">
            @foreach (var item in Model.ParentIDs)
            {
                if (Model.ParentID == item.id)
                {
                     <option value="@item.id" selected>@item.title</option>
                }
                else
                {
                     <option value="@item.id">@item.title</option>
                }
            }
        </select>
    }