I’m trying to make a comment section for my site. After a comment has been posted I would like to show it immediately instead of being forced to reload the page. So I need to somehow be able to create div and other elements and later fill them with the relevant data.
$(document).ready(function () {
$(".commentAnswer").keypress(function (e) {
if (e.which == 13) {
var commentData = { Value: ($(input).attr("data-answerId")),
Description: ($(input).attr("value"))
};
$.ajax({
type: "POST",
url: '@Url.Action("SubmitComment", "Home")',
data: JSON.stringify(commentData),
dataType: "json",
contentType: 'application/json, charset=utf-8',
traditional: true,
success: function (data) {
//create elements.
}
});
}
});
This the block I want to create.
<div class="commentContent">
<div class="comment">@comment.Comment.Text</div>
<ul>
<li>
<div class="newsTime">@comment.User.FirstName @comment.User.LastName</div>
</li>
<li>- </li>
<li>
<div class="newsTime">
@foreach (var role in comment.CommenterRoles) {
if (role.Role.Equals("Authenticated") || role.Role.Equals("Administrator")) {
//Don't write anything
} else {
@role.Role@:.
}
}
</div>
</li>
<li>- </li>
<li>
<div class="newsTime">
@Project.Tools.TimeTool.ToTimeSinceString(comment.Comment.SubmitDateTime)
</div>
</li>
</ul>
</div>
<hr />
This is a very basic example of how to add comment dynamically. Whitout more information on what data is returned I cant help much more. This makes the assumption that your Action returns a partial view for that single comment.
JSFiddle containing example markup:
http://jsfiddle.net/HenryGarle/SMbxk/
My recomendations:
Create a partial view that displays a single comment.
Inside of your comments do a foreach loop calling the partial passing through a single comment object. i.e:
Comment.cshtml:
This is where you place your repeated mark up.
SubmitComment action:
Return the partial Comment.cshtml with the newly added Comment
This means there will be no extra data being passed around.
The other approach is to take the information posted in and add the markup yourself using the prepend (Or append, depending on your needs) Or as nayish has mentioned, use the clone but again although this is a little more manual and you’ll end up managing the markup in two places instead of one. Using these methods would make maintaining it a pain in the long run.