【发布时间】:2017-01-09 08:37:57
【问题描述】:
我在网站上工作,我想在帖子中添加 cmets,一切都在使用 Html.Begin 表单,但每次我添加评论时页面都会刷新。
我用 Ajax.BeginForm 替换了 Html.BeginForm 但我必须刷新页面才能看到评论。 我添加了 jquery.unobtrusive-ajax.js 但仍然无法正常工作。
控制器:
public PartialViewResult Comments(string id)
{
return PartialView("Comments", _dc.Comments.Where(m => m.Id_P == id).OrderByDescending(m => m.Date).ToList());
}
public ActionResult AddComment(string id, string comment)
{
Comment com = new Comment();
com.Id = Guid.NewGuid().ToString();
com.Id_A = AccountInfo.Id;
com.CommentT = comment;
com.Id_P = id;
com.Date = String.Format("{0: dd MMM 'at' HH:mm}", DateTime.Now);
_dc.Comments.Add(com);
_dc.SaveChanges();
return RedirectToAction("Index", "Home");
}
查看:
<div class="article-comments">
<div class="post-comm">
@Html.Action("Comments", "Post", new { id = item.Id })
@using (Ajax.BeginForm("AddComment", "Post", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "post-comm" }))
{
<input type="hidden" id="id" value="@item.Id" name="id" />
<div class="form-group">
<div class="col-md-12">
<input class="form-control" placeholder="enter your comment..." name="comment" id="comment">
</div>
</div>
}
</div>
</div>
我试过了,但现在正在刷新页面
public JsonResult AddComment(string id, string comment)
{
Comment com = new Comment();
com.Id = Guid.NewGuid().ToString();
com.Id_A = AccountInfo.Id;
com.CommentT = comment;
com.Id_P = id;
com.Date = String.Format("{0: dd MMM 'at' HH:mm}", DateTime.Now);
_dc.Comments.Add(com);
_dc.SaveChanges();
return Json("success");
}
观点:
<div class="post-comm">
@Html.Action("Comments", "Post", new { id = item.Id })
</div>
<form method="post" onsubmit="addComment('@item.Id', this)">
<div class="form-group">
<div class="col-md-12">
<input class="form-control" placeholder="enter your comment..." name="comment" id="comment">
</div>
</div>
</form>
还有ajax调用
function addComment(idP, el) {
var comm = $(el).find("#comment").val()
$.ajax({
url: "/Post/AddComment/",
type: "POST",
data: { id: idP, comment: comm },
async: true,
success: function (data) {
$(".post-comm").load("@Html.Action('Comments', 'Post', new { id = "+ idP +"})")
},
error: function (xhr) {
alert("error - comment post");
}
});}
【问题讨论】:
-
您收到错误信息还是只是刷新?如果您只是对控制器进行 jquery.ajax 调用并返回包含新添加的注释的部分视图,您不认为会更容易吗?最后一行中的redirecttoaction 似乎是问题所在。
-
你不应该有 RedirectToAction("Index", "Home");在 Ajax 方法中
-
您进行 ajax 调用但尝试在 POST 方法中重定向(ajax 调用从不重定向)。您需要返回部分视图(以及为什么要替换整个表单)
-
那我应该返回什么?
标签: jquery ajax asp.net-mvc asp.net-mvc-5