System.Collections.Generic.IEnumerable <myblogsite.models.blog post>'不包含'Categories'的定义</blogsite.models.blog post>

时间:2013-07-13 19:15:04

标签: asp.net-mvc-4

这是我的BlogPost Model类:

    public class BlogPost
{
    public int Id { get; set; }
    public string Title { get; set; }

    [AllowHtml]
    public string ShortDescription { get; set; }

    [AllowHtml]
    public string PostBody { get; set; }

    public string Meta { get; set; }
    public string UrlSlug { get; set; }        
    public DateTime PostedOn { get; set; }
    public DateTime? Modified { get; set; }

    public virtual ICollection<BlogPostCategory> Categories { get; set; }
    public virtual ICollection<BlogPostTag> Tags { get; set; }
}

这是我的BlogPostCategory Model类:

    public class BlogPostCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string UrlSlug { get; set; }
    public string Description { get; set; }

    // Decared virtual because the data must be returned from another table.
    public virtual ICollection<BlogPost> BlogPosts { get; set; }
}

每个类都属于一个单独的Controller / View。

最后,这是博客索引视图的顶部端口:

@model IEnumerable<MyBlogSite.Models.BlogPost>

@{
   ViewBag.Title = "Index";
 }

@Html.RenderPartial("~/Views/Category/_Categories.cshtml", Model.Categories );

<p>
   @Html.ActionLink("New Blog Post", "Create")
</p>
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Title)
    </th>
    ....

在传递Model.Categories的视图中,我从这篇文章的标题中获取异常。在我看来,我已经在BlogPost模型中定义了类别。我做错了什么?

1 个答案:

答案 0 :(得分:1)

Razor页面上的模型是IEnumerable<MyBlogSite.Models.BlogPost>。您似乎正在尝试显示有关集合中每个项目的信息。如果是这样,那么您可以遍历它们或创建显示/编辑器模板,并分别使用@Html.DisplayFor(x => x)@Html.EditorFor(x => x)

@foreach(var post in Model) {
    <p>Do stuff here with the local "post" variable.</p>
}

这里是a link to Scott Gu's blog在Razor视图中讨论@model指令。