我有public ICollection<Comment> Comments { get; set; }
的博客模型和评论模型。我已经为文章创建了视图(详细信息视图(,我想显示从模型博客(没有问题(和对文章的评论到评论以及评论之后的所有内容,然后显示向博客添加评论的表单(不在其他页面中,我希望它在博客的视图中(。
public class BlogPost
{
public int BlogPostID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public ICollection<Comments>Comments {get;set;}
}
public class Comments
{
public int BlogPostID { get; set; }
public string Comment { get; set; }
public DateTime dateTime { get; set; }
public virtual BlogPost BlogPost { get; set; }
}
查看
@model projectMvc.Model.BlogPost;
<div>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => mode.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Body )
</dt>
<dd>
@Html.DisplayFor(model => model.Movie.Body )
</dd
</dl>
</div>
@if (Model.Comments != null)
{
foreach (var comment in Model.Comments)
{
@Html.Partial("_Comment", comment)
}
}
它显示博客数据,并有部分视图的所有评论博客。现在我不知道如何添加表单来添加评论。非常感谢。
要添加评论,您可以在视图中添加以下语法,用于显示添加评论的文本框和提交评论的按钮
<div class="AddComment" style="margin-left: 30%; margin-bottom: 5px; margin-top: 8px;">
<input type="text" id="@string.Format("{0}_{1}", "comment", post.BlogPostID)" class="form-control" placeholder="Add a Comment ..." style="display: inline;" />
<button type="button" class="btn btn-default addComment" data-id="@post.PostID"><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
</div>
</div>
点击按钮后,您可以使用ajax 从控制器调用适当的操作
$('.addComment').on('click', function () {
var postId = $(this).attr('data-id');
var commentMsg = $('#comment_' + postId).val();
var dateTimeNow = new Date();
//alert('Hello');
var comment = {
CommentMsg: commentMsg,
CommentedDate: dateTimeNow.toLocaleString()
};
$.ajax({
type: 'POST',
url: '@Url.Action("AddComment", "Comments")',
data: { comment, postId },
success: function (response) {
$('div[class=allComments_' + postId + ']').remove();
var allCommentsArea = $('<div>').addClass('allComments_' + postId);
allCommentsArea.html(response);
allCommentsArea.prependTo('#commentsBlock_' + postId);
},
error: function (response) {
alert('Sorry: Something Wrong');
}
});
});