簡體   English   中英

在視圖中顯示模型

[英]Display model in View

我是一個MVC Noob,但我真的想獲得一些使用MVC的經驗,所以我嘗試使用MVC重新創建一個Asp Classic項目。 下面的代碼不會顯示與膳食/索引頁面上的菜單相關的膳食列表。

我已經閱讀了幾個不同的模式,ninject和自動映射器,然而,從我可以告訴它,在處理簡單的關聯時,這是不必要的。

我只想將菜單添加到菜單中並匯總每個菜單的餐價。

楷模:

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. 
}

菜單控制器:

 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; } }編輯:

問題是EF對列表類型導航屬性需要兩件事:1) ICollection類型和2)屬性上的virtual

因此,如果您將Meals屬性更改為以下內容,您應該是好的:

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

ICollection的原因是EF的返回值是IQueryable類型。 虛擬的原因是EF實際上返回代理類而不是實際的模型類。 這些代理具有覆蓋返回數據集的導航屬性的覆蓋。 如果您的屬性不是虛擬的,則EF無法覆蓋它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM