我想在一個視圖中添加兩個模型: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