Ajax 模态不更新目标 ID

Ajax Modal Not Updating Target ID

本文关键字:目标 ID 更新 模态 Ajax      更新时间:2023-09-26

我有以下模式向博客添加评论,但是当我提交表单而不是使用所有添加的评论列表更新目标 id 时,它会重定向到带有评论列表的新页面?如何更新目标 ID,使其与所有其他注释一起显示新注释?

 <button type="button" class="btn btn-primary" data-toggle="modal"    data-target="#myModal"> Launch demo modal</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
    @using (Ajax.BeginForm("AddComment", "Blog", new AjaxOptions
                {
                    HttpMethod = "POST",
                    InsertionMode = InsertionMode.Replace,
                    UpdateTargetId = "comments",
                    LoadingElementId = "progress",
                    OnSuccess = "$('#myModal').modal('hide');"
                }))
      {
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">Add Comment</h4>
        </div>
        <div class="modal-body">
             @Html.ValidationSummary(true)
             @Html.HiddenFor(model => model.Blog.BlogID)
             <div class="form-group">
                 @Html.LabelFor(model => model.BlogComment.Comment)
                 @Html.TextAreaFor(model => model.BlogComment.Comment, 4, 104, new { @class = "form-control" })
                 @Html.ValidationMessageFor(model => model.BlogComment.Comment)
             </div>
        </div>
        <div class="modal-footer">
           <button type="button" class="btn btn-primary">Save changes</button>
           <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
        </div>
      }
  </div>
 </div>
</div>

<div id="comments">
   @Html.Action("Comments", "Blog", new { id = Model.Blog.ID })
</div>

public PartialViewResult Comments(int id)
{
    IEnumerable<BlogComment> CommentList = _repository.GetBlogComments(id);
    return PartialView("_BlogComments", CommentList);
}
public ActionResult AddComment(// All Pramameters)
{
     if (ModelState.IsValid)
     {
          // Do Save Comment
          if (Request.IsAjaxRequest()) 
          {
             return RedirectToAction("Comments", new { id = id });
          }
     }
     else
    {
        //return to modal with errors
         return PartialView("_CreateComment", BlogViewModel);
     }
 }

RedirectToAction将触发客户端重定向。

将返回更改为此,只需调用返回PartialViewResult的现有方法:

 if (Request.IsAjaxRequest()) 
 {
     return Comments(id);
 }

更新

另请参阅下面的评论以了解另一个方面,即不显眼的 ajax 和 jquery 验证更新。