求asp.net mvc4的帖子的回复和评论功能的实现的例子,在文本区域内输入文字,然后点击提交,
这主要是用到了ajax获取后台数据的方法,具体代码见附件,以下是部分代码:
Controller部分代码:
[HttpPost]
public ActionResult Comment(Comments entity)
{
var session = 0;
if (Session["UserName"] != null)
{
entity.Comment_Content = HttpUtility.HtmlDecode(entity.Comment_Content);
entity.MemberID = Convert.ToInt32(Session["UserName"].ToString());
session = 0;
}
else
{
session = 1;
}
CommentsFacade.Add(entity);
int dataid = Convert.ToInt32(entity.MemberID);
var dataname = MemberFacade.GetFiltered(p => p.MemberID == dataid).Select(p => p.MemberName).FirstOrDefault();
var datatime = entity.UpdateDate.ToString("yyyy年MM月dd日 HH:mm");
return Json(new { msg = "ok", data = entity.Comment_Content, dataName = dataname, dataTime = datatime, dataSession = session }, JsonRequestBehavior.AllowGet);
}
View部分代码:
window.onload = function () {
var oBtn = document.getElementById('Comment');
var oUl = document.getElementById('ul1');
oBtn.onclick = function (evt) {
var dataform = $("#dataform");
var oLi = document.createElement('li');
var url = dataform.attr("action");
var params = $(dataform).serialize();
$.post(url, params, function (data) {
var msg = data.msg;
if (data.dataSession == 0) {
if (msg == "ok") {//成功
alert("保存成功");
var content = "<table style='width: 100%; height: 100%;'>" +
"<tr>" +
" <td>" + data.data + "</td>" +
" </tr>" +
" <tr style='text-align: right;'>" +
" <td><font style='font-weight: bold'>评论者:</font>" + data.dataName + " <font style='font-weight: bold'>评论时间:</font>" + data.dataTime + "</td>" +
" </tr>" +
" </table>" +
" <hr style='background: #ccc; height: 5px; margin-top: -7px;' />";
oLi.innerHTML = content;
if (oUl.children.length > 0) {
oUl.insertBefore(oLi, oUl.children.length);
}
else {
oUl.appendChild(oLi);
}
//运动
var iHeight = oLi.offsetHeight;
oLi.style.height = '0';
startMove(oLi, { height: iHeight }, 6, function () {
startMove(oLi, { opacity: 100 }, 6);
});
}
else {
alert("保存失败!");
}
}
else {
window.location = "/Home/NoSession2";
return;
}
});
}
}