我想在 html.dropdownlist 中显示带有缩进的项目
这是控制器中的代码
IEnumerable<ViewModels.testvm> test = db.Database.SqlQuery<ViewModels.testvm>(@"WITH tree (id, parentid, level, title, rn) as
(
some code
)
***********SELECT id,REPLICATE(' ',level) + title as title
FROM tree
order by RN");
ViewBag.ParentID = new SelectList(test, "ID", "Title");
如您所见,我将 添加到了 replecate 中的下拉项
但问题是 显示在下拉列表中。
这是视图>源结果:
<select class="form-control" id="ParentID" name="ParentID"><option
value="10">Menu1</option>
<option value="11">&nbsp;Sub1</option>
<option value="14">&nbsp;Submenu1</option>
<option value="12">Menu2</option>
<option value="16">&nbsp;sub2</option>
<option value="13">Menu3</option>
<option value="15">&nbsp;sub3</option>
<option value="17">&nbsp;&nbsp;sub sub</option>
<option value="22">&nbsp;&nbsp;&nbsp;sub3 sub sub</option>
<option value="19">menu4</option>
<option value="20">&nbsp;sub4</option>
<option value="21">menu5</option>
</select>
如您所见
转换为 &nbsp;
我尝试了
"\xA0"
而不是  
,但它也显示在下拉列表中!
我认为 html.raw 可以解决这个问题,但我不知道如何将它与 html.dropdownlist 一起使用。
这是视图
<div class="col-md-10">
@Html.DropDownList( "ParentID", null, htmlAttributes: new { @class = "form-
control" })
</div>
有什么想法吗?
编辑
通过像这样改变视图,问题就解决了: 我在检查帖子作为答案后尝试了这个
<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>
假设您将集合放置在名为
ParentIDs
的 ViewModel 成员中,您可以手动创建下拉列表:
景色:
@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>
}
在尝试使用
TM
在下拉选项中渲染 ™
符号时,我遇到了类似的问题。我能够通过使用扩展类中的 .Replace()
方法来解决此问题,以便将 &
转换回 &
private static MvcHtmlString CustomItemDropDownListFor(MvcHtmlString source, string sourceItemName, string sourceItemValue = "", string targetItemValue = "")
{
string htmlString = source.ToHtmlString();
htmlString = htmlString.Replace("&", "&");
return new MvcHtmlString(htmlString);
}