ASP.NET and JQuery Comment Submission Form
This post (long overdue) is to build off of my last one. I will show you a very simple, high level overview of how to create a comment form in ASP.NET and post comments asynchronously with JQuery.
viewStory.aspx (relevant sections)
<div id="commentSection">
<asp:Repeater ID="Comments" runat="server">
<ItemTemplate>
<div class="comment">
<span class="commentDate">Posted on <%# Eval("PostedDate") %> by <%# Eval("PostedBy") %></span>
<span class="commentText"><%# Eval("CommentText") %></span>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div id="commentForm">
<asp:TextBox ID="commentText" runat="server" TextMode="MultiLine" Rows="7" Columns="15" />
<asp:Button ID="addCommment" runat="server" Text="Add Comment" />
</div>
<div visible="false">
<asp:Label ID="userID" runat="server"></asp:Label>
<asp:Label ID="storyID" runat="server"></asp:Label>
</div>
viewStory.aspx.cs (told you this was simple and a high level overview)
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
userID = MyUserAttributes.ID.ToString();
storyID = Request.QueryString["story"];
// Populate the story and bind existing comments to the repeater
}
[System.Web.Services.WebMethod()]
public static string AddComment(string commentText, int userID, int storyID)
{
// Validation logic would go here (how many posts by this user in the past x minutes)
// Scrub the input string from any unallowed tags eg - <script>, <html> <body>
// Insert the comment into the database via stored procedure
// The stored procedure would then return all the data for the new comment
if (dataTable.Rows.Count > 0)
{
StringBuilder newCommentHtml = new StringBuilder();
newCommentHtml.AppendLine("<div class=\"comment\">");
newCommentHtml.AppendLine("<span class=\"commentDate\">");
newCommentHtml.Append("Posted on ");
newCommentHtml.Append(dataTable.Rows[0]["PostedDate"].ToString());
newCommentHtml.Append(" on ");
newCommentHtml.Append(dataTable.Rows[0]["PostedBy"].ToString());
newCommentHtml.Append("</span>");
newCommentHtml.AppendLine("<span class=\"commentText\">");
newCommentHtml.Append(dataTable.Rows[0]["CommentText"].ToString());
newCommentHtml.Append("</span>");
return newCommentHtml.ToString();
}
else
{
return "<div class=\"error\">Oops, your comment could not be added at this time, please try again later!</div>";
}
}
}
and finally… the relevant javascript
$('#addComment').click(function() {
// Hide the comment form
// Strip out or escape dangerous characters.
$('#commentForm').hide();
$.ajax({
type: "POST",
url: "viewStory.aspx/AddComment",
data: "{'commentText':'" + $('#commentText').val() + "', 'userID':'" + $('#userID').html() + "','storyID':'" + $('#storyID').html() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Display the newly posted comment
$('#commentSection .comment:last').after(msg.d);
}
});
})
Comments (0)