在上图中双击 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调用第二个parial视图,实际上它得到相同的数据。
这是否可以仅使用单一呼叫更新两个部分视图,例如仅调用 FirstParialView
答案 0 :(得分:1)
你确实可以做到这一点我所做的就是我创建了一个函数,它将部分视图呈现在一个变量中,比如
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);
}
});
}