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

asp.net-mvc-3 entity-framework

Question

I have a model that resembles this in several ways:

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

I'd want to be able to display Customer Name rather than CustomerID on the Notes Details view. Naturally, I would use a dropdown list if this were a Create or Edit view. However, in a read-only Details page, I'm not sure how to display the value rather than the ID.

Thanks!

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

Accepted Answer

Code First focuses mostly on code rather than database logic.

Therefore, you'll feel more comfortable having a reference property instead of having Foreign Keys (like CustomerID) in your models (it's also feasible, and sometimes essential, but not usually).

public virtual Customer Customer {get;set;}

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

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

Remember to obtain your Notes object along with any associated entities or attributes required by your View or 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