Pau*_*les 7 ajax asp.net-mvc post-redirect-get
我正在为我的所有表单使用post-redirect-get模式,但现在需要添加AJAX功能来改善用户体验.我最初的想法是两者不混合.
在PRG场景中,我会发布我的帖子操作,如果存在验证错误,则会重定向回我的get操作,否则重定向到我的成功获取操作.
在AJAX场景中,我需要以任一方式返回局部视图.更典型的是,我会首先检查它是否是一个AJAX请求.如果是,则返回局部视图,否则返回视图.
有什么想法或建议吗?
我们在应用程序中使用 Post-Redirect-Get。这是我们所做工作的本质,它围绕方法Request.IsAjaxRequest()
并将视图拆分为 .aspx,每个 .aspx 托管一个 .ascx,以便每个 can 操作都可以同步和异步调用(即通过 Ajax)。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Foo foo)
{
try
{
// Save the changes to the data store
unitOfWork.Foos.Attach(foo);
unitOfWork.Commit();
if (Request.IsAjaxRequest())
{
// The name of the view for Ajax calls will most likely be different to the normal view name
return PartialView("EditSuccessAsync");
}
else
{
return RedirectToAction("EditSuccess");
}
}
catch (Exception e)
{
if (Request.IsAjaxRequest())
{
// Here you probably want to return part of the normal Edit View
return PartialView("EditForm", foo);
}
else
{
return View(foo);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我们对此也有一个轻微的变体,我们专门从xValRulesException
中捕获's (以便以不同于其他“更严重”异常的方式处理模型验证错误。
catch (RulesException re)
{
re.AddModelStateErrors(ModelState, "");
return View(foo);
}
Run Code Online (Sandbox Code Playgroud)
话虽如此,有时我会偷偷怀疑我们可能做得有点不对。