Ajax 从操作返回PartialView到特定div
我正在玩弄jQueryUI和partialView,遇到了一个无法解决的问题 此位的工作原理与我预期的一样:Ajax 从操作返回PartialView到特定div,ajax,asp.net-mvc,razor,partial-views,Ajax,Asp.net Mvc,Razor,Partial Views,我正在玩弄jQueryUI和partialView,遇到了一个无法解决的问题 此位的工作原理与我预期的一样: <div> @Ajax.ActionLink("Test Me!", "dialogtest", new { id = Model.Id }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "dialogtest-view" })</td> </di
<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>
并返回一个PartialView,显示在目标div中。jQuery+jQueryUI用于将此div作为模式对话框弹出。测试的第一部分完成了
现在让我们假设返回的PartialView只是一个带有文本框的基本表单,大致如下:
@using (Html.BeginForm("DialogTest", "pages", FormMethod.Post))
{
@Html.HiddenFor(x => x.Id)
@Html.TextBoxFor(x => x.Name)
<button type="submit">Test Me!</button>
}
但是,如果我使操作未通过验证,而不是再次将PartialView指向div,它将重新绘制整个页面(这显然会丢失jQuery UI对话框)
我想要的是:如果验证失败,只需更新包含表单的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>
}
当然,在javascript文件中定义相应的成功回调:
function success(result) {
if (result.redirectUrl) {
window.location.href = result.redirectUrl;
}
}
很好,谢谢你。唯一的区别是我必须使用$.parseJSON来获取重定向url。
@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") });
}
function success(result) {
if (result.redirectUrl) {
window.location.href = result.redirectUrl;
}
}