在MVC4中插入相关数据

时间:2013-08-10 13:32:03

标签: c# asp.net-mvc-4 ef-code-first

我有这两个模型类:

 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; }
    }

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

2 个答案:

答案 0 :(得分:0)

您可以为此创建viewmodel:

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

在控制器中:

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

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

在视图中,您可以添加以下新评论项:

  @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" })
    }

答案 1 :(得分: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>
相关问题