Show display values ​​for a foreign key property in a model

I have a model that looks something like this:

public class Notes { public int NoteID {get; set;} public string Note {get; set;} public int CustomerID {get; set;} { 

In the Notes Details view, I would like to include the customer name instead of CustomerID. Obviously, if it was a Create or Edit view, I use a drop-down list. However, I'm not sure how to show the value, not the identifier in the Read-Only view.

Thanks!

+4
source share
1 answer

Code First is mainly ... code, not database logic.

So, instead of having foreign keys (e.g., CustomerID) in your models (this is also possible, and sometimes necessary, but not always), you will be more comfortable having a reference property

 public virtual Customer Customer {get;set;} 

So, in your opinion, having Notes as a Model, you can simply use

 @Html.DisplayFor(m => m.Customer.Name); 

When you retrieve a Notes object, be sure to specify the related objects / properties needed for your View / ViewModel (I'll talk about lazy loading)

+7
source

Source: https://habr.com/ru/post/1412066/


All Articles