Reputation: 67
I have blog model with public ICollection<Comment> Comments { get; set; }
and comment model. I have created view for article (Details view) and I want to show everything from model blog (not problem) and comments to article to and after comments then show form for adding comment to blog (not in other page, I want it in the view with blog).
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; }
}
View
@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)
}
}
It shows the blog data and there is partial view for all comments to blog. And now I am not sure how to add form for adding comments. Thank you.
Upvotes: 0
Views: 265
Reputation: 2019
To add comments you can add below syntax in your view for displaying textbox for adding comment and button for submitting comments
<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>
After that on click of button you can call appropriate action from the controller using 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');
}
});
});
Upvotes: 1