如何使用一次 ajax 调用更新不同的局部视图

how to update different Partial view using one ajax call

在上图中,双击 div(第一张图片),然后双击 查看对话框(第二张图片)案例内容打印相同的数据但结构不同

控制器

  [HttpPost]
  public ActionResult FirstParialView(long ID)
  {
      //inserted some data into database Here

    List<TimetableDetails> timetableObs =unitofWork.TimetableDetails.ToList();
     return PartialView("DayStructure/_FirstView", timetableObs);
  }   

  [HttpPost]
  public ActionResult SecondParialView(long ID)
  {
    List<TimetableDetails> timetableObs =unitofWork.TimetableDetails.ToList();
     return PartialView("DayStructure/_SecondView", timetableObs);
  } 

Ajax 调用(此Ajax 在对话框中设计和工作)

 @using (Ajax.BeginForm("FirstParialView", "timetable", new { area = "User" },
                        new AjaxOptions { OnSuccess = "ViewMPlan"))
{
      //Inserted Some data using submit button here. and view both parial view
}

javascript

 function ViewMPlan(response) {
   //print first Parial View
   $('#firstParialView').html(response);
  //for second parial view
    $.ajax({
                url: "/user/timetable/SecondParialView",
                type: "POST",
                dataType: "JSON",
                data: { ID: ID},
                success: function (response) {
               $('#SecondParialView').html(response);
          }
        });
    }

在上述情况下,我必须单独 ajax 调用第二个局部视图,实际它获得相同的数据。

是否可以像仅调用 FirstParialView

那样仅使用单个调用来更新两个局部视图

你确实可以做到这一点我所做的是我创建了一个函数,它将在一个变量中呈现我的部分视图,就像这样

private string RenderPartialView(string viewName, object model)
        {
            ViewData.Model = model;
            using (System.IO.StringWriter writer = new System.IO.StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, writer);
                viewResult.View.Render(viewContext, writer);

                return writer.GetStringBuilder().ToString();
            }
        }

现在您需要更改您的操作结果,例如

[HttpPost]
public JsonResult AjaxCallFunc(long ID)
{
List<TimetableDetails> timetableObs =unitofWork.TimetableDetails.ToList();
var partialView1 = RenderPartialView("DayStructure/_FirstView", timetableObs);
var partialView2 = RenderPartialView("DayStructure/_SecondView", timetableObs);
return Json(new{View1=partialView1,View2=partialView2 },JsonRequestBehaviour.DenyGet);
}

然后你的控制器到

unction ViewMPlan(response) {
   //print first Parial View
   $('#firstParialView').html(response);
  //for second parial view
    $.ajax({
                url: "/user/timetable/AjaxCallFunc",
                type: "POST",
                dataType: "JSON",
                data: { ID: ID},
                success: function (response) {
                $('#FirstPartialView').html(response.View1);
               $('#SecondParialView').html(response.View2);
          }
        });
    }