从数据库中获取虚拟IEnumerable

本文关键字:虚拟 IEnumerable 获取 数据库 | 更新日期: 2023-09-27 18:18:10

我正试图将dropdownlistfor绑定到来自数据库的列表

模型

public class Actor
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    ...
    // I have a database table called genre
    [ForeignKey("Genre")]
    public virtual IEnumerable<Genre> Genres { get; set; }
}

在控制器

    // GET: Actors/Create
    public ActionResult Create()
    {
        Actor actor = new Actor();
        actor.Genres = new // Believe I need to do something here...
        return View(actor);
    }

在视图

    <div class="form-group">
        @Html.LabelFor(model => model.Genres, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="dropdown">
                @Html.DropDownListFor(M => M.Genre, new SelectList(Model.Genres, "Value", "Text"))
            </div>
        </div>
    </div>

我需要做什么?

谢谢

从数据库中获取虚拟IEnumerable

我通常会给我的ViewModel添加一个类型为IEnumerable<SelectListItem>的属性:

public class ActorViewModel
{
     public int GenreId { get; set; }
     public IEnumerable<SelectListItem> Genres { get; set; }
}

然后在我的Controller中,我会添加一个方法,将为您返回这些:

public IEnumerable<SelectListItem> GetGenres() 
{
     foreach (var genre in dbContext.Genres)
     {
          yield return new SelectListItem 
              {
                  Value = genre.Id.ToString(),
                  Text = genre.Name
              };
     }
}

然后设置如下:

viewModel.Genres = this.GetGenres();

然后在我的View

@Html.DropDownListFor(m => m.GenreId, Model.Genres, "Please select")

您应该为此创建ViewModel

public class ActorViewModel
{
    public Actor actor { get; set; }
    public SelectList Genres { get; set; }
    public int GenreId { get; set; }
}

创建一个以选择列表形式返回类型的方法

 public SelectList GetAsSelectList()
    {
        var genres = (from s in GetAllGenres()
                        select new
                        {
                            s.Id, s.Name
                        }).ToList();
        return new SelectList((IEnumerable)genres, "Id", "Name");
    }

在你的控制器中填充模型属性:

var model = new ActorViewModel
{
    actor = new Actor(),
    Genres = GetAsSelectList(),
    GenreId = 0
};
return View(model);

在视图中:

@Html.DropDownListFor(M => M.GenreId, Model.Genres,"--Select--")