我对一个下拉列表有很大的问题,因为我需要他不是强制性的。我找到了一些可以为 null 类型的解决方案,例如 int?,但这仅适用于 int、datetime 等,但我在模型中的类型是其他对象(引用)。简单地说,我有团队结构,有些团队没有父团队,因此引用应该为空,那么我该如何做才能不必选择下拉列表,并且我得到父团队的空值
模型(简化):
public class Team
{
public Team ParentTeam { get; set; }
}
Controller :
var listTeam = (from team in listOfTeams.AsEnumerable()
select new SelectListItem
{
Text = team.Name,
Value = team.ID.ToString()
}).ToList();
SelectList dropDownlistOfTeams = new SelectList(listTeam, "Value", "Text");
并查看:
<div class="form-group">
@Html.LabelFor(model => model.ParentTeam, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.ParentTeam, (SelectList)ViewBag.ListOfTeams, "-- Set Parent --")
</div>
</div>
提前非常感谢。
最佳答案
在 Controller 中,只需添加一个空团队即可。
listTeam.Add(new SelectListItem() {Text="None", Value=null});
关于c# - 使用 DropdownFor 将 null 作为默认值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115160/