我是ASP MVC的新手,我正在尝试构建一个简单的博客应用程序。
我有以下帖子模型:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace ASPress.Models
{
public class Posts
{
public Posts() => Comments = new HashSet<Comments>();
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string Summary { get; set; }
public long AuthorId { get; set; }
[Display(Name = "Published")]
[DataType(DataType.Date)]
public DateTime DatePublish { get; set; }
public Users Author { get; set; }
public ICollection<Comments> Comments { get; set; }
}
}
评论模型:
using System;
using System.Collections.Generic;
namespace ASPress.Models
{
public partial class Comments
{
public long Id { get; set; }
public string Comment { get; set; }
public long PostId { get; set; }
public Posts Post { get; set; }
}
}
在我的控制器中,我试图通过帖子获取评论:
public async Task<IActionResult> Details(long? id)
{
var posts = await _context.Posts
.Include(p => p.Author)
.Include(p => p.Comments)
.SingleOrDefaultAsync(m => m.Id == id);
return View(posts);
}
在我的帖子视图中,我调用的部分视图应该显示帖子的评论:
@Html.Partial("Comments", Model.Comments)
部分观点:
@model IEnumerable<ASPress.Models.Comments>
<ul>
@foreach (var item in Model) {
<li>@Html.DisplayFor(modelItem => item.Comment)</li>
}
</ul>
但即使数据库中存在数据,也没有显示任何内容。 这主要是来自dotnet mvc命令工具的代码脚手架。