我想在一个视图中添加两个模型:CommentVM和BlogVM。评论VM - 评论, BlogVM - postDetails。 我尝试通过ajax添加评论到我的数据库,并通过我的两个模型来查看。但是,当我尝试显示我的网页时,我收到错误,我的对象为null(commentVM) 下面的代码我的控制器 任何消化我做错了什么? 感谢您的帮助!添加评论 - 在一个视图中的两个模型
// GET: Admin/Blog/kategoria/{name}/post/id
[ActionName("post")]
public ActionResult PostDetails(int id)
{
//Declare BlogVM
BlogVM model;
CommentVM model2;
int id2;
using (Db db = new Db())
{
//Get the page
BlogDTO dto = db.Blog.Find(id);
//Confirm page exist
if (dto == null)
{
return Content("Taka strona nie istnieje!");
}
//Init BlogVM
model = new BlogVM(dto);
id2 = dto.Id;
// CommentDTO dto2 = db.Comments.Find(x => x.PostId == id2);
model2 = new CommentVM();
}
var finalItem = new DetailsComment
{
Blog = model,
Comment = model2
};
return View("PostDetails", finalItem);
}
代码我的模型:
public class CommentVM
{
public CommentVM()
{
}
public CommentVM(CommentDTO row)
{
Id = row.Id;
Name = row.Name;
Body = row.Body;
PostId = row.PostId;
CreatedAt = row.CreatedAt;
}
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Body { get; set; }
public int PostId { get; set; }
public DateTime CreatedAt { get; set; }
//public IEnumerable<CommentVM> CommentDetails { get; set; }
}
public class BlogVM
{
public BlogVM()
{
}
public BlogVM(BlogDTO row)
{
Id = row.Id;
Title = row.Title;
Slug = row.Slug;
Body = row.Body;
CategoryName = row.CategoryName;
CategoryId = row.CategoryId;
CreatedAt = row.CreatedAt;
Sorting = row.Sorting;
HasSidebar = row.HasSidebar;
}
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Title { get; set; }
public string Slug { get; set; }
[Required]
[StringLength(int.MaxValue, MinimumLength = 3)]
[AllowHtml]
public string Body { get; set; }
public string CategoryName { get; set; }
[Required]
public int CategoryId { get; set; }
public DateTime CreatedAt { get; set; }
public int Sorting { get; set; }
public bool HasSidebar { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
public class DetailsComment
{
public BlogVM Blog { get; set; }
public CommentVM Comment { get; set; }
public IEnumerable<CommentVM> CommentDetails { get; set; }
}
在我看来
@foreach (var item in Model.CommentDetails)
{
<tr>
<td>
<div class="ajaxdivtd"></div>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreatedAt)
</td>
</tr>
}
你'finalItem'变量只设置值'Blog'和'Comment',而不是'CommentDetails'。 – sleeyuen
为什么在DetailsComment类中有CommentVM对象和CommentVM列表?根据我的理解,你会对特定的帖子有很多评论,是吗? –
是的,我有很多评论到一个职位 – damian17