ASP.NET MVC List/Detail View Show Name Values
In my list and details view I need t开发者_开发问答o show the value (name) instead of the id (int). The catch is I only have one collection. So only the the EnteredBy name is showing. The Model.Entries.Staff only contains one item not all possible matches.
// model
public class Entry
{
[Display(Name = "Assigned To")]
[Column(Name = "AssignedToId")]
[Required(ErrorMessage = "You must select an individual.")]
public int AssignedToId { get; set; }
[Display(Name = "Entered By")]
[Column(Name = "EnteredById")]
[Required(ErrorMessage = "You must select an individual.")]
public int EnteredById { get; set; }
public virtual Staff Staff { get; set; }
}
// view
@foreach (var item in Model.Entries)
{
<td>
@(item.AssignedToId == null ? "None" : item.Staff.Name))
</td>
<td>
@(item.EnteredById == null ? "None" : item.Staff.Name)
</td>
}
Have you considered using a ViewModel pattern to solve this?
The way I usually do this is I create a ViewModel class that contains both the Model for the page and a property that holds the the list values for my lookup. Here is an example:
In my View I have (Razor):
@Html.DropDownListFor(model => model.ModelObject.leagueId,
new SelectList(Model.LeagueList, "leagueId", "leagueName"),
"--Select League--", "name='ModelObject.leagueId'")
ModelObject is my actual editable Model...
Then in my ViewModel I have:
public LeagueSeasonRoList LeagueList { get; set; }
public Team ModelObject { get; set; }
In my model, I have a leagueId property which ties it all together.
Then in the controller, instead of using the Editable object directly as my model, I use the ViewModel.
You'll need to make a few adjustments so all your references are correct but I have used this pattern many times with success.
hth,
\ ^ / i l l
精彩评论