c# - 使用 DropdownFor 将 null 作为默认值传递

标签 c# asp.net-mvc drop-down-menu

我对一个下拉列表有很大的问题,因为我需要他不是强制性的。我找到了一些可以为 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/

相关文章:

asp.net-mvc - 在 MVC3 中下载 Azure Blob 文件

c# - 使用 NodaTime 将特定国家日期时间转换为 UTC

c# - 连接尝试失败,因为连接方在一段时间后没有正确响应或连接的主机未能响应

c# - 使用 Json 将具有两个对象的 View 模型传递给 Controller

c# - 下拉绑定(bind)方法不起作用

html - 推特 Bootstrap : drop-down menu class not working

jquery - 禁用单选按钮单击上的下拉框

c# - 通过在循环内添加更多元素来扩展 foreach 循环

C# : DBConnection. Open() 超时太长

jquery - Ajax GET 永远不会成功,但 POST 可以(相同的代码)