mvc gets virtual IEnumerable from the database

advertisements

I am trying to bind a dropdownlistfor to a list that comes from the database

In the model

public class Actor
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    ...

    // I have a database table called genre
    [ForeignKey("Genre")]
    public virtual IEnumerable<Genre> Genres { get; set; }

}

In the controller

    // GET: Actors/Create
    public ActionResult Create()
    {
        Actor actor = new Actor();

        actor.Genres = new // Believe I need to do something here...
        return View(actor);
    }

In the view

    <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>

What is it i need to do?

Thanks


I would usually add a property to my ViewModel that is of type IEnumerable<SelectListItem>:

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

Then in my Controller I would add a method that will return these for you:

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

Then set as so:

viewModel.Genres = this.GetGenres();

Then in my View

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