fejesjoco
fejesjoco

Reputation: 11903

In ASP.NET MVC, how to make a dropdown for a related entity, instead of a foreign key property?

Let's say I have this model:

public class Category {
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Item {
    public long Id { get; set; }
    public string Name { get; set; }
    //public long CategoryId { get; set; }
    public Category Category { get; set; }
}

I want to edit an item on my page, I have a list of categories.

I could easily create a dropdown for the CategoryId property. But I need to have the entire Category entity mapped instead of just a foreign key. Is there a conventional, generic way to do that?

Upvotes: 0

Views: 114

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239350

No, because you cannot set the value attribute of an option to an entire entity, let alone post that back in a format that the modelbinder could recognize. The proper way to handle this is that you post to the foreign key property and then save.

If your problem is that you do not have a foreign key property (because you've relied on EF conventions to create it for you based on the Category property), then your best bet is to utilize a view model in your view instead of the actual entity. In that view model, you can include the CategoryId property and use that for your dropdown. Then, once you receive the model back in your POST action, you use the id to query the database and retrieve the actual object. You then set Category on your entity to this object and save.

Upvotes: 1

Related Questions