display name for reference entity in mvc

asp.net-mvc asp.net-mvc-5 c# entity-framework entity-framework-6

Question

I have two entities which are generated from data first approach of entity framework in MVC5. Following are the Models

public partial class Cuisine
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Dish> Dishes { get; set; }
}


public partial class Dish
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CuisineId { get; set; }

    public virtual Cuisine Cuisine { get; set; }
}

When I display the Dishes it is showing as below

enter image description here

But I want the column names as Name and Cuisine Name instead of Name and Name. How to do that? I want to display as Name when showing Cuisine list and Cuisine Name when showing in Dish list.

Code for my cshtml

<table class="table">
<tr>
<th>
    @Html.DisplayNameFor(model => model.Name)
</th>
<th>
    @Html.DisplayNameFor(model => model.Cuisine.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
    @Html.DisplayFor(modelItem => item.Name)
</td>
<td>
    @Html.DisplayFor(modelItem => item.Cuisine.Name)
</td>
<td>
    @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
    @Html.ActionLink("Details", "Details", new { id=item.Id }) |
    @Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
1
0
2/12/2016 9:17:03 AM

Popular Answer

It would probably be a good idea to use a ViewModel, which aggregates just the properties you need for your view.

public class DishVm
{
        public int Id { get; set; }

        [Display(Name="Cuisine Name")]
        public string Name { get; set; }

        [Display(Name="Name")]
        public string DishName { get; set; }
}

I don't know how you are retrieving your data, but it would look similar to this:

IEnumerable<DishVm> vm = context.Dishes
                                .Include(c => c.Cuisines)
                                .OrderBy(n => n.Name)
                                .Select(x => new DisVm {
                                    Name = x.Cuisine.Name,
                                    DishName = x.Name
                                 });

return View(vm);

Your view would then have a new model type: @model IEnumerable<Yournamespace.Folder.DishVm>

3
2/12/2016 9:22:32 AM


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