在视图中显示ICollection

时间:2012-11-16 22:55:37

标签: c# .net asp.net-mvc razor

我有一个从我的SQL数据库自动生成的模型。

class Organization
{
    public Organization()
    {
        this.ContactTitles = new HashSet<ContactTitle>();
        this.OrganizationAddresses = new HashSet<OrganizationAddress>();
        this.OrganizationBusinessTypes = new HashSet<OrganizationBusinessType>();
        this.OrganizationCountries = new HashSet<OrganizationCountry>();
        this.OrganizationEmails = new HashSet<OrganizationEmail>();
        this.OrganizationMemberships = new HashSet<OrganizationMembership>();
        this.OrganizationNotes = new HashSet<OrganizationNote>();
        this.OrganizationPhones = new HashSet<OrganizationPhone>();
        this.OrganizationWebsites = new HashSet<OrganizationWebsite>();
        this.Contacts = new HashSet<Contact>();
        this.OrganizationIndustryCodes = new HashSet<OrganizationIndustryCode>();
    }

    public int OrganizationID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ContactTitle> ContactTitles { get; set; }
    public virtual ICollection<OrganizationAddress> OrganizationAddresses { get; set; }
    public virtual ICollection<OrganizationBusinessType> OrganizationBusinessTypes { get; set; }
    public virtual ICollection<OrganizationCountry> OrganizationCountries { get; set; }
    public virtual ICollection<OrganizationEmail> OrganizationEmails { get; set; }
    public virtual ICollection<OrganizationMembership> OrganizationMemberships { get; set; }
    public virtual ICollection<OrganizationNote> OrganizationNotes { get; set; }
    public virtual ICollection<OrganizationPhone> OrganizationPhones { get; set; }
    public virtual ICollection<OrganizationWebsite> OrganizationWebsites { get; set; }
    public virtual ICollection<Contact> Contacts { get; set; }
    public virtual ICollection<OrganizationIndustryCode> OrganizationIndustryCodes { get; set; }
 }

在我的组织视图中,在我的索引页面上 - 它被强类型化为我的组织模型。

我正在尝试在组织索引页面上显示我认为应该在ICollection中的成员资格信息。除非我错过了解释它的作用。

当我使用@Html.DisplayFor(modelItem => item.OrganizationMemberships.来获取OrganizationMembership表中的数据时,它不会显示在IntelliSense上。我只需要能够显示数据,我不必用表单提交任何更改。

1 个答案:

答案 0 :(得分:3)

由于模型是可枚举的类型 - @model PagedList.IPagedList<VAGTC.Models.Organization> - 您需要在主视图中迭代它们:

@foreach (var organization in Model)
{
    @Html.DisplayFor(model => organization)
} 

接下来,为班级Organization创建display template。在Views/Shared/DisplayTemplates下添加视图Organization.cshtml

@model VAGTC.Models.Organization

现在这是渲染你的类的主视图。在这里,您可以迭代会员资格项目:

@foreach (var membership in Model.OrganizationMemberships)
{
    @Html.DisplayFor(model => membership)
} 

现在再次通过在OrganizationMembership下添加OrganizationMembership.cshtmlViews/Shared/DisplayTemplates课程创建部分视图。