MVC 中的绑定下拉列表

binding dropdown list in MVC

您好,我正在尝试通过模型在 MVC 中绑定我的下拉列表。

这是我的模型

[Table("FileConfig")]
public class FileConfigModel
{
    [Key]
    [Display(Name = "File Congif ID")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int FileConfigId { get; set; }
    ....
    [Display(Name = "Description")]
    public string Description { get; set; }
}

这是我在控制器中的 getall 方法:

public List<FileConfigModel> GetAll()
{
    return db.FileConfigModels.ToList();
}

然后我从我的另一个控制器调用它

public ActionResult Create()
{
     var fileConfigListEntries = new FileConfigController().GetAll()
        .Select(fc => new SelectListItem
        {
            Value = fc.FileConfigId.ToString(),
            Text = fc.Description,
            Selected = false
        });
    ViewBag.FileConfigEntires = fileConfigListEntries;
    return View();
}

这是我的观点:

@Html.LabelFor(model => model.FileConfigId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.DropDownListFor(model => model.FileConfigId, ViewBag.FileConfigEntires as SelectList, "-Select File Config")
    @Html.ValidationMessageFor(model => model.FileConfigId)
</div>

但是,我一直收到错误提示

"There is no ViewData item of type 'IEnumerable' that has the key 'FileConfigId'.."

有人可以帮助我并告诉我我错过了什么吗。

上述错误的可能原因可能是变量 fileConfigListEntries 为空或未从 dbcontext 获取数据。 由于下拉列表以 null 或集合为界,没有元素错误出现 "There is no ViewData item of type 'IEnumerable' that has the key 'FileConfigId'.." 我建议用 hard-coded 数据替换 fileConfigListEntries 视图包数据,然后看到错误消失。

您的查询 fileConfigListEntries(即 ..Select(fc => new SelectListItem{ .. })returns IEnumerable<SelectListItem>

在视图中,您然后尝试使用 ViewBag.FileConfigEntires as SelectList

将其转换为 typeof SelectList

SelectListIEnumerable<SelectListItem>,但是IEnumerable<SelectListItem>不是SelectList ,因此转换失败,DropDownListFor()的第2个参数为null。当第二个参数是 null 时,该方法期望第一个参数是 IEnumerable<SelectListItem> 而不是,因此出现异常。

将代码更改为

@Html.DropDownListFor(m => m.FileConfigId, ViewBag.FileConfigEntires as IEnumerable<SelectListItem>, ... )

@Html.DropDownListFor(model => model.FileConfigId, (IEnumerable<SelectListItem>)ViewBag.FileConfigEntires, ... )

旁注 .Select 子句中没有点设置 Selected = false - 默认情况下是 false,但在任何情况下,绑定到模型时都会忽略它 属性(它的 属性 的值决定了选择的内容)