这是如何设置的:
public class HomeController : Controller
{
public ActionResult MainAction()
{
return View();
}
[ChildActionOnly]
public ActionResult Index()
{
return PartialView();
}
[ChildActionOnly]
public ActionResult Create()
{
return PartialView();
}
[HttpPost]
public ActionResult ProcessCreate(SomeViewModel model)
{
return PartialView("Index");
}
}
以及相应的观点:
~/Views/Home/MainAction.cshtml
:
<div>
This is the main view
</div>
<div id="indexContainer">
@{Html.RenderAction("Index");}
</div>
~/Views/Home/Index.cshtml
:
<div>
This is the index view @DateTime.Now.ToLongTimeString()
</div>
<div>
@{Html.RenderAction("Create");}
</div>
~/Views/Home/Create.cshtml
:
@using (Ajax.BeginForm("ProcessCreate", "Home", new AjaxOptions { UpdateTargetId = "indexContainer" }))
{
<button type="submit">OK</button>
}
另外不要忘记包含jquery.unobtrusive-ajax.min.js
Ajax.* 助手工作的脚本:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
你会注意到我已经重命名了 Create POST 动作,否则当 Html.RenderAction 助手在表单回发后被调用时,它将再次执行 POST 动作,你将陷入无限循环。