0

View - MovieForm.cshtml:

<div class="form-group">
    @Html.LabelFor(m => m.Movie.GenreId)
    @Html.DropDownList(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Name"), "Select a Genre", new { @class = "form-control" })
</div>

View model - MovieFormViewModel:

public class MovieFormViewModel
{
    public IEnumerable<Genre> Genres { get; set; }
    public Movies Movie { get; set; }  
}

Model classes:

public class Movies
{
    public int Id { get; set; }
    [Required]
    [StringLength(255)]
    public string Name { get; set; }
    [Required]
    public Genre Genre { get; set; }
    public int GenreId { get; set; }
    public DateTime ReleaseDate { get; set; }
    public DateTime DateAdded { get; set; }
    public int NumberInStock { get; set; }
}

public class Genre
{
    public int Id { get; set; }
    [Required]
    [StringLength(255)]
    public string Name { get; set; }
}

Controller - MoviesController:

public ActionResult NewMovie(int id)
{
    var movie = _context.Movies.SingleOrDefault(m => m.Id == id);
        
    var viewModel = new MovieFormViewModel
        {
            Movie = movie,
            Genres = _context.Genres.ToList()
    };

    return View("MovieForm", viewModel);
}

My DbSet is:

public DbSet<Genre> Genres { get; set; }

The only problem I have is in my view (MovieForm.cshtml).

This line of markup

@Html.LabelFor(m => m.Movie.GenreId)

doesn't cause any errors, however this

@Html.DropDownList(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Name"), "Select a Genre", new { @class = "form-control" })

throws an error

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

This error is in m.Movie.GenreId which was was working fine in the previous line.

1
  • 2
    Change DropDownList to DropDownListFor. Commented Jun 11, 2022 at 18:05

1 Answer 1

1

Change DropDownList to DropDownListFor.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.