Ajax模式不更新目标ID

时间:2015-06-19 10:09:03

标签: javascript jquery ajax asp.net-mvc bootstrap-modal

我有以下模式为博客添加评论但是当我提交表单而不是用所有添加的评论列表更新目标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);
     }

 }

1 个答案:

答案 0 :(得分:1)

RedirectToAction将触发客户端重定向。

更改您的返回,而只是调用返回PartialViewResult的现有方法:

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

<强>更新

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