我如何在视图中使用此模型
public class PostDetailsViewModel
{
public Post Posts1 { get; set; }
public IEnumerable<Post> Posts2 { get; set; }
}
视图
@model IEnumerable<forum3.ViewModels.PostDetailsViewModel>
@foreach (var item in Model)
{
<span>@item.Posts1.Title</span><br />
<p>@item.Posts1.Question</p><br /><br />
}
控制器
public ViewResult PostDetails(int id)
{
PostDetailsViewModel postdetailsviewmodel = new PostDetailsViewModel();
postdetailsviewmodel.Posts1 = postRepository.Find(id);
postdetailsviewmodel.Posts2 = postRepository.FindPostByParentIds(id);
List<PostDetailsViewModel> postDetailsList = new List<PostDetailsViewModel>();
postDetailsList.Add(postdetailsviewmodel);
return View(postDetailsList);
}
如何在视图中使用post2作为答案
答案 0 :(得分:1)
假设您要显示问题列表及其答案,并将View模型设为这样。
(我将Post1更改为Question并将Posts2更改为Answers以提高可读性)
public class PostDetailsViewModel
{
public Post Question { get; set; }
public List<Post> Answers { get; set; }
}
public class Post
{
public int ID { set; get; }
public string Title { set; get; }
}
假设你的控制器返回一个PostDetailsViewModel列表,PostDetailsViewModel有一个类型为Post的Post类和问题属性的问题属性
public ActionResult Posts()
{
List<PostDetailsViewModel> objVMLsit = new List<PostDetailsViewModel>();
//add the object to objVMList here
return View(objVMLsit);
}
此视图将为您提供输出
@model List<MvcApplication1.Models.PostDetailsViewModel>
@foreach (var item in Model)
{
<h2>@item.Question.Title</h2><br />
foreach (var answer in item.Answers)
{
<p>@answer.Title</p>
}
}
编辑:看到您的控制器操作方法后,我想您想要显示特定帖子(问题)及其答案。因此,只需将一个PostViewModel对象从操作返回到您的视图,而不是返回它们的列表
public ViewResult PostDetails(int id)
{
PostDetailsViewModel postdetailsviewmodel = new PostDetailsViewModel();
postdetailsviewmodel.Question= postRepository.Find(id);
postdetailsviewmodel.Answers= postRepository.FindPostByParentIds(id);
return View(postdetailsviewmodel);
}
然后像这样更改你的视图
@model MvcApplication1.Models.PostDetailsViewModel
<h2>@Model.Question.Title</h2><br />
@foreach (var answer in Model.Answers)
{
<p>@answer.Title</p>
}