将空字符串添加到selectList作为SelectedValue

时间:2014-03-04 12:12:11

标签: c# asp.net-mvc

我正在使用从数据库中检索的数据填充DropdownList。我想添加默认的空字符串。我正在尝试使用SelectedValue property而没有任何效果。我已尝试nullstring.empty,如下面的示例

ViewBag.Project = new SelectList(unitOfWork.projectRepository.Get(), "ProjectName", "ProjectName",string.Empty);

View中的DropDownList声明

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

转换为:

<select class="form-control" id="Project" name="Project">
    <option value="Sample project">Sample project</option>
    <option value="Second project">Second project</option>
</select>

由于String.Empty没有选项。

我应该在代码中更改

正如@Alexander建议我用ToList转换它,现在这是我的代码:

var items = unitOfWork.projectRepository.Get();
items=items.ToList<Project>().Insert(0, new Project { ProjectId = 1, ProjectName = "" });
ViewBag.Project = new SelectList(items, "ProjectName", "ProjectName",string.Empty);

但这引发了异常:Error Cannot implicitly convert type 'void' to 'System.Collections.Generic.IEnumerable<magazyn.Models.Project>

1 个答案:

答案 0 :(得分:3)

SelectList不包含接受空默认选项的重载。您可以手动将其添加到项目集合中:

var items = unitOfWork.projectRepository.Get();
items.Insert(0, new Item {ProjectId = null, ProjectName == "", });

ViewBag.Project = new SelectList(items, "ProjectName", "ProjectName",string.Empty);

<强>更新

关于其他转换例外:您正尝试将Insert函数的结果分配给List。使用此代码:

var items = unitOfWork.projectRepository.Get().ToList();
items.Insert(0, new Project { ProjectId = 1, ProjectName = "" });
相关问题