简体   繁体   中英

Display model in View

I'm an MVC Noob but I really want to gain some experience using MVC so I am trying recreate an Asp Classic project using MVC. The code below does't not display the list of meals associated with a menu on the Meals/Index page.

I have read about several different patterns, ninject and auto mapper however, from what I can tell it's nothing like that is necessary when dealing with a simple association.

I would just like to add Meals to a Menu and aggregate the meal prices for each menu.

Models:

public class Meal
{   [Key]
    public int MealId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public int MenuId { get; set; }
}


public class Menu
{
    [Key]
    public int MenuId { get; set; }
    public DateTime WeekendServed { get; set; }
    public decimal Price { get; set; }
    public List<Model> Meals { get; set; //Menus have meals. 
}

Menu Controller:

 public ViewResult Index()
 {
    return View(unitOfWork.MenuRepository.Get());
 }

Menu/Index/ :

@model IEnumerable<Skimos.Models.Meal>
----

<Table Headers>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.WeekendServed)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @foreach (var meal in item.Meals)
            {
                @Html.Display(meal.Name)
                @Html.Display(meal.Description)
                @Html.Display(meal.Price.ToString())
            }
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.MenuId }) |
            @Html.ActionLink("Details", "Details", new { id=item.MenuId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.MenuId })
        </td>
    </tr>
}

MenuRepository public IQueryable Menus { get { return context.Menus; } } public IQueryable Menus { get { return context.Menus; } } Edit:

The issue is that EF requires two things for list-type navigation properties: 1) an ICollection type and 2) virtual on the property:

So if you change your Meals property to the following, you should be good:

public virtual ICollection<Meal> Meals { get; set; }

The reason for ICollection is that the return value from EF will be an IQueryable type. The reason for the virtual is that EF actually returns proxy classes instead of the actual model class. These proxies have overrides for the navigation properties that return the datasets. If your property is not virtual, EF can't override it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM