我在玩jQuery UI和PartialViews,遇到了一个我无法解决的问题。
这个比特正如我所期望的那样工作:
<div>
@Ajax.ActionLink("Test Me!", "dialogtest", new { id = Model.Id }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "dialogtest-view" })</td>
</div>
<div id="dialogtest-view">
</div>
这是对这种行动方法的
[HttpGet]
public PartialViewResult DialogTest(int id)
{
//pretend to get something from DB here
var vm = new DialogUITestVM();
return PartialView("uidialog_partial", vm);
}
并返回一个PartialView,它显示在目标div中。jQuery+jQueryUI用于将该div弹出为模式对话框。测试的第1部分完成!
好的,现在让我们假设返回的PartialView只是一个带有文本框的基本表单,大致如下:
@using (Html.BeginForm("DialogTest", "pages", FormMethod.Post))
{
@Html.HiddenFor(x => x.Id)
@Html.TextBoxFor(x => x.Name)
<button type="submit">Test Me!</button>
}
这是张贴回控制器罚款-
[HttpPost]
public ActionResult DialogTest(DialogUITestVM vm)
{
//arbitrary validation so I can test pass and fail)
if (vm.Name.Equals("Rob"))
{
//error!
vm.ErrorMessage = "There was an error you numpty. Sort it out.";
return PartialView(vm);
}
//hooray it passed - go back to index
return RedirectToAction("index");
}
但是,如果我使操作未通过验证,而不是再次将PartialView指向div,它会重新绘制整个页面(这显然会丢失jQueryUI对话框)。
我想要的是:如果验证失败,只需更新包含表单的div
。
我哪里错了?
您可以在分部中使用Ajax表单,而不是普通表单,并在AjaxOptions:中使用OnSuccess回调
@using (Ajax.BeginForm("DialogTest", "pages", new AjaxOptions { UpdateTargetId = "dialogtest-view", OnSuccess = "success" }))
{
@Html.HiddenFor(x => x.Id)
@Html.TextBoxFor(x => x.Name)
<button type="submit">Test Me!</button>
}
然后分别修改您的控制器动作:
[HttpPost]
public ActionResult DialogTest(DialogUITestVM vm)
{
//arbitrary validation so I can test pass and fail)
if (vm.Name.Equals("Rob"))
{
//error!
vm.ErrorMessage = "There was an error you numpty. Sort it out.";
return PartialView(vm);
}
//hooray it passed - go back to index
return Json(new { redirectUrl = Url.Action("Index") });
}
当然,在javascript文件中定义相应的成功回调:
function success(result) {
if (result.redirectUrl) {
window.location.href = result.redirectUrl;
}
}