我正在为所有表单使用post-redirect-get模式,但现在需要添加
AJAX功能来改善用户体验.我最初的想法是两者不混合.
在PRG场景中,我会发布我的帖子操作,如果存在验证错误,则会重定向回我的get操作,否则重定向到我的成功获取操作.
在AJAX场景中,我需要以任一方式返回局部视图.更典型的是,我会首先检查它是否是一个AJAX请求.如果是,则返回局部视图,否则返回视图.
有什么想法或建议吗?
解决方法
我们在我们的应用中使用Post-Redirect-Get.这是我们所做工作的本质,它取决于Request.IsAjaxRequest()方法,并将您的视图拆分为.aspx,每个都托管.ascx,以便可以同步和异步(即通过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); } } }
我们还有一个轻微的变体,我们专门捕获RulesException(从xVal开始,以便将模型验证错误与其他“更严重”的异常区别对待).
catch (RulesException re) { re.AddModelStateErrors(ModelState,""); return View(foo); }
尽管如此,有时我会怀疑我们可能会略微做错.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。