Display specific field found by Id Entity Framework 6

Viewed 30

I have thse two classes. The code works, I can add a Movie to an actor and viceversa. However, on the frontend side I cannot display the Name of the entity I'm adding, I can only display the Id number. If I use a DropDownListFor I can display the names of the actors but I can only save an actor through the Id field. How do I make it so that I display only the actor name and still save it on the database?

public class Movie
{
    [Key]
    public int Id { get; set; } 

    public string Title { get; set; }  

    public int ActorId { get; set; }

    [ForeignKey("ActorId")]
    public ICollection<Actor> Actors { get; set; }

    public int DirectorId { get; set; }

    [ForeignKey("DirectorId")]
    public Director Director { get; set; }    
}

public class Actor
{
    [Key]
    public int Id { get; set; } 
    public string Name { get; set; }

    public int MovieId { get; set; }
    
    [ForeignKey("MovieId")]
    public ICollection<Movie> CreditedMovies { get; set; }
}
1 Answers

For your scenario you required view model with properties of DD as well.

MovieViewModel.cs

public class MovieViewModel
{
 public Movie Movie{get;set;}
 public List<SelectListItem> ActorDD {get;set;}
}

using above view model you will need to bind your DD like below

Controller


public ActionResult Home()
{
    MovieViewModel model = new MovieViewModel();   
    model.ActorDD.Add(new SelectListItem { Text = "Actor1", Value = "1" });  
    model.ActorDD.Add(new SelectListItem { Text = "Actor2", Value = "2" });  
    model.ActorDD.Add(new SelectListItem { Text = "Actor3", Value = "3" });  
    return View(model);  
}

Your view look like below.

Razor.cshtml


@Html.DropDownListFor(m=>m.Movie.ActorId, model.ActorDD)
Related