1
웹 사이트에서 작업 중이며 게시물에 주석을 추가하려고합니다. 모든 것이 Html.Begin 양식과 함께 작동하지만 주석을 추가 할 때마다 페이지가 새로 고칩니다.MVC 5 Ajax.Begin 양식이 UpdateTargetId를 대체하지 않습니다.
나는 Html.BeginForm을 Ajax.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="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>
:
<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");
}
뷰를 상쾌
그리고 AJAX 호출 내가 finnaly을했다, 그래서
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 호출은 리디렉션되지 않습니다). 부분보기를 반환해야합니다 (어쨌든 전체 양식을 대체하는 이유는 무엇입니까?) –