In a model, show the display values for a foreign key property.

asp.net-mvc-3 entity-framework

Question

I have a model that looks kinda like this:

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

On the Notes Details view, I would like to be able to show Customer Name instead of CustomerID. Obviously if this were a Create or Edit view I use a dropdown list. However I am not sure how to show the value and not the ID in a read only Details view.

Thanks!

1
4
5/11/2012 7:38:57 PM

Accepted Answer

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

So, instead of having the Foreign Keys (like CustomerID) in your models (it's also possible, and sometimes needed, but not always), you'll be more confortable having a reference property

public virtual Customer Customer {get;set;}

So in your view having Notes as Model, you could simply use

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

When you retrieve your Notes entity, don't forget to include the related entities / properties needed for your View / ViewModel (I let you read about lazy loading)

8
5/11/2012 8:31:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow