MVC在视图中显示相关的子实体

时间:2013-03-25 23:11:51

标签: asp.net-mvc eager-loading

我正在尝试在MVC 4应用程序中构建一个视图,该应用程序将显示域模型以及来自其相关子实体的所有数据,但由于某些原因,我无法在视图中访问子项的属性。 Intellisense没有看到它们。

这是我的域模型,名为Subscribers:

public class Subscriber
{

    [Required]
    [Display(Name = "Subscriber ID")]
    public int SubscriberId { get; set; }

    [Required]
    [DataType(DataType.DateTime)]
    [Display(Name = "Date Created")]
    public DateTime DateCreated { get; set; }

    //set to money in DB
    [Display(Name = "Credits (Money owed to customer)")]
    private static decimal _Credits = 0;
    public decimal Credits { get { return _Credits; } set { _Credits = value; } }

    //set to money in DB
    [Display(Name = "Debits (Money owed to us)")]
    private static decimal _Debits = 0;
    public decimal Debits { get { return _Debits; } set { _Debits = value; } }

    public List<UserProfile> Users { get; set; }

    public List<Website> Websites { get; set; }

    public List<Order> Orders { get; set; }

    public List<SubscriberNote> SubscriberNotes { get; set; }

}

如您所见,订阅者有一堆相关的子实体。这是我的控制器代码,它使用了一种急切的加载方法:

public ActionResult Edit(int id = 0)
    { 
        var Subscriber = db.Subscribers
                           .Where(s => s.SubscriberId == id)
                           .Include(s => s.Users)
                           .Include(s => s.SubscriberNotes)
                           .Include(s => s.Orders)
                           .Include(s => s.Websites.Select(w => w.DomainNames))
                           .FirstOrDefault();

        return View(Subscriber);
    }

这里是我的控制器:

@model PpModels.Models.Subscriber

@{
ViewBag.Title = "Edit";
}


@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Subscriber</legend>

    @Html.HiddenFor(model => model.SubscriberId)


    --deleted fro brevity--

    --Problem is below--

    <div class="editor-label">
        @Html.LabelFor(model => model.Users.FirstName)
    </div>    

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

MVC不喜欢model.Users.FirstName。我如何访问这些值?非常感谢!

1 个答案:

答案 0 :(得分:0)

您必须循环此属性,因为它是ListUsers不会拥有FirstName属性,但其中的每个用户都会。

@foreach(var user in model.Users)
{
    <div class="editor-label">
        @Html.LabelFor(model => user.FirstName)
    </div>
    ....  
}