ASP.Net MVC#另一个viewmodel中的两个viewmodel-如何在视图中引用

ASP.Net MVC#另一个viewmodel中的两个viewmodel-如何在视图中引用,c#,asp.net-mvc,asp.net-mvc-3,razor,C#,Asp.net Mvc,Asp.net Mvc 3,Razor,我试图通过使用ViewModels来遵循建议的最佳实践 在我的论坛应用程序中,我想发布帖子列表,并在屏幕底部添加一个文本框,以便可以发布回复 所以在我看来,我需要一个用于帖子列表的ViewModel,以及一个用于发布回复的ViewModel(TopicId和Content) 因此,我认为我需要在第三个ViewModel中将这两个ViewModel组合在一起,在我的视图中,迭代ViewModel的Posts部分,然后在底部创建一个表单,其中我有ViewModel的Reply部分,回发只将Reply

我试图通过使用ViewModels来遵循建议的最佳实践

在我的论坛应用程序中,我想发布帖子列表,并在屏幕底部添加一个文本框,以便可以发布回复

所以在我看来,我需要一个用于帖子列表的ViewModel,以及一个用于发布回复的ViewModel(TopicId和Content)

因此,我认为我需要在第三个ViewModel中将这两个ViewModel组合在一起,在我的视图中,迭代ViewModel的Posts部分,然后在底部创建一个表单,其中我有ViewModel的Reply部分,回发只将ReplyViewModel发送给控制器

我的ViewModels是:

 public class PostViewModel
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Author { get; set; }
    public DateTime DateOfTopic { get; set; }
}

public class ReplyViewModel
{
    public int TopicId { get; set; }
    public string Content { get; set; }
}

public class PostListAndReplyVM
{
    public List<PostViewModel> PostViewModel { get; set; }
    public ReplyViewModel ReplyViewModel { get; set; }
}
在我看来,我有:

@model IEnumerable<centreforum.Models.PostListAndReplyVM>

<table class="table table-condensed table-striped table-hover table-bordered">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.PostId)
    </th>
....
....
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.PostId)
    </td>
…但这就产生了错误:

“centreform.Models.postlistandeplyvm”不包含“PostId”的定义,并且找不到接受“centreform.Models.postlistandeplyvm”类型的第一个参数的扩展方法“PostId”

对于列表部分:

@foreach (var item in Model.PostViewModel) 
…给出了以下错误:

“System.Collections.Generic.IEnumerable”不包含“PostViewModel”的定义,并且找不到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的扩展方法“PostViewModel”

我肯定我错过了一些简单的东西-谢谢你的帮助


Mark

我认为您的视图出错,您在控制器上返回了PostListAndReplyVM,并且您的视图引用了PostListAndReplyVM的IEnumerable

您必须更改视图中声明的模型

@model centreforum.Models.PostListAndReplyVM

希望有帮助

Hi-这很有意义,谢谢-但是现在当我尝试引用:@Html.DisplayNameFor(model=>model.PostViewModel.PostId)我发现错误:“System.Collections.Generic.List”不包含“PostId”的定义,并且找不到接受“System.Collections.Generic.List”类型的第一个参数的扩展方法“PostId”-因此我的视图仍然不正确-感谢您的帮助。您好,model.PostViewModel是一个集合,您必须在它之前循环!
@foreach (var item in Model.PostViewModel) 
@model centreforum.Models.PostListAndReplyVM