0

Here is my BlogPost Model class:

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

Here is my BlogPostCategory Model class:

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

Each class belongs to a separate Controller/View.

Finally, here is the top port of the Index View for Blog:

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

In the View where Model.Categories is being passed in is where I am getting the exception from the title of this post. It seems to me that I have defined Categories within the BlogPost Model. What am I doing wrong?

4

1 回答 1

1

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

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

这是Scott Gu 的博客的链接,讨论@modelRazor 视图中的指令。

于 2013-07-13T19:46:07.183 回答