mvc从数据库中获取虚拟IEnumerable

时间:2015-10-16 11:50:41

标签: c# asp.net-mvc

我正在尝试将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>

我需要做什么?

由于

2 个答案:

答案 0 :(得分:0)

您应该为此

创建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--")

答案 1 :(得分:0)

我通常会向属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")