正在将模型加载到 HTML DropDownListFor 助手

Loading model to HTML DropDownListFor helper

我有一个名为 Region 的简单模型,类似于

namespace App
{
    using System;
    using System.Collections.Generic;

    public partial class Region
    {
        public int RegionID { get; set; }
        public string RegionDescription { get; set; }
    }
}

我正在尝试将模型加载到 HTML DropDownListFor() 视图中的助手中,例如

@model IEnumerable<App.Region>

<div class="row">
    @Html.DropDownListFor("RegionList",
                    new SelectList(model => model.RegionDescription),
                    "Select Region",
                    new { @class = "form-control" })

</div>

@model IEnumerable<App.Region>
<div class="row">
    @Html.DropDownListFor("RegionList",
                        new SelectList(s => s.RegionDescription),
                        "Select Region",
                        new { @class = "form-control" })

</div>

或:

@model IEnumerable<App.Region>
<div class="row">
@foreach (var item in Model)
{
    @Html.DropDownListFor("RegionList",
                        new SelectList(model => item.RegionDescription),
                        "Select Region",
                        new { @class = "form-control" })
}
</div>

但在这两种方式中我都遇到了这个错误。

Cannot convert lambda expression to type 'object' because it is not a delegate type

为什么会发生这种情况,我该如何解决?

SelectList 构造函数将集合作为第一个参数。不是 lamda 表达式!您使用的辅助方法不正确!

理想情况下,Html.DropDownListFor 方法的第一个参数是一个表达式,助手可以从中获取视图模型的值 属性。这意味着,要使用它,您的视图模型应该有一个 属性 来存储选定的选项值。所以创建一个像这样的视图模型

public class CreateVm
{
  public int SelectedRegion { set;get;}
  public List<SelectListItem> Regions { set;get;}
}

现在在您的 GET 操作中,您需要创建此视图模型的对象,加载区域集合 属性 并将其发送到视图

public ActionResult Create()
{
  var vm = new CreateVm();
  vm.Regions = new List<SelectListItem>{
         new SelectListItem { Value="1", Text="Region1"},
         new SelectListItem { Value="2", Text="Region2"},
         new SelectListItem { Value="3", Text="Region3"}
  };
  return View(vm);
}

并且在你的视图中,这个新视图模型是强类型的,你可以像这样使用 DropDownListFor 辅助方法

@model CreateVm
@Html.DropDownListFor(x=>x.SelectedRegion,Model.Regions,"Select Region",
                                                            new { @class = "form-control" })

如果您确实想使用传递给视图的现有视图model/type,您可以考虑使用Html.DropDownList辅助方法来呈现一个SELECT 元素

@Html.DropDownList("SelectedRegion", 
                    new SelectList(Model, "RegionID", "RegionDescription"), "Select Region",
                    new { @class = "form-control" })

这将呈现名称为 "SelectedRegion"

的 SELECT 元素