0

我有这两个模型类:

 public class Article
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public ICollection<Comment> Comments { get; set; }
    }
    public class Comment
    {
        public int ID { get; set; }
        public int ArticleID { get; set; }
        public string CommentTxt { get; set; }
        public Article Article { get; set; }
    }
    public class ArticleDbContext : DbContext
    {
        public DbSet<Article> Articles { get; set; }
        public DbSet<Comment> Comments { get; set; }
    }

现在我想要一个页面,列出为一篇文章插入的所有评论,并且在列表的下面我可以为那篇文章插入新评论?

4

2 回答 2

0

You can create viewmodel for this:

public class ArticleViewModel
{ 
   public Article Article { get; set; }
   public List<Comment> Comments { get; set; }
}

In controller:

public ActionResult Details(int id)
{
   ArticleViewModel model = new ArticleViewModel();

   model.Article = _yourDBRepository.GetArticleById(id);
   model.Comments = _yourDBRepository.LoadCommentsByArticleId(id);
   return View(model);
}

In view you can add new comment item like this:

  @using (Html.BeginForm("Create", "Comment", FormMethod.Post))
    {
      @Html.Hidden("ArticleId", Model.Article.Id)
      @Html.TextBox("text", "", new { name = "text", id = "text", data_placeholder = "Enter comment" })
    }
于 2013-08-10T15:53:05.567 回答
0

在控制器中

//** Get Article
Public ActionResult Article (int ID)
{
Article article = db.Find(ID);
return(article)
}

//*Add comments
[HttpPost]
public ActionResult Addcomment (int articleID, string CommentTxt)
{
  Article article = db.Find(ID);
  Comment comment = new Comment();
  db.Comments.Add(comment);
  comment.ArticleID = articleID;
  comment.CommentTxt = CommentTxt;
  db.SaveChanges;

  return PartialView(article);
}


//**Get List of comments after adding new comment
public ActionResult AllComments(int articleID)
{
  Article article = db.Find(ID);
  var comments = db.Comments.Where(a=>a.ArticleID == articleID).ToList();
  return PartialView(comments);
}

在您的文章视图中:

<sript>
$('.addComment')click(function(){
$post('/Home/Addcomment?articleID=@Model.ID&CommentTxt='+$('.commenttext').val()).always(function()
{
$('.comments).Load(/Home/AllComments/articleID=@Model.ID)
});
})
</script>

 //*Your article here
......

 //*Comments section
<div class="comments">@Html.RenderAction("AllComments", "Home")</div>

<input type="text" class="commenttext" />
<button class="addComment">Add comment</button>

在您的 AllComments 视图中

<ul>
@foreach(var i in Model)
<li>
@i.CommentTxt 
</li>
</ul>
于 2013-08-10T18:15:57.883 回答