后/状态改变后MVC3模型验证的最佳实践重定向 [英] MVC3 model validation best practice redirect after post / state change

查看:147
本文介绍了后/状态改变后MVC3模型验证的最佳实践重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于web应用程序应该在POST(或更改服务器端状态的任何非重复的请求)...

Given that web apps should always redirect after a POST (or any non-repeatable request to change server-side state) ...

...如何使用MVC3模型验证的和人的执行强制重定向?

... how are people using MVC3 Model Validation and performing the mandatory redirect?

推荐答案

通常你只有一个的成功的职位(没有模型验证错误)后重定向,否则你一个验证错误信息发送回页面

Usually you only redirect after a successful post (no Model Validation errors), otherwise you send back the page with a validation error message.

重定向的在<一个href=\"http://www.eworldui.net/blog/post/2008/05/ASPNET-MVC---Using-Post2c-Redirect2c-Get-Pattern.aspx\">PRG模式prevents双张贴,所以没有害处发回相同的页面(+错误信息),因为后期没有成功,也不会,除非有新的变化,以验证通过。

The redirect in the PRG pattern prevents double-posting, so there's no harm to send back the same page (+ error message) because the post was not successful and will not be unless something changes to make validation pass.

修改

看起来你正在寻找通过的ModelState 下(转移)请求。这可以通过使用的TempData 存储的ModelState 到下一个请求来实现。仅供参考,的TempData 使用会话。

It looks like you're looking for passing ModelState to the next (redirected) request. This can be done by using TempData to store ModelState up to the next request. FYI, TempData uses Session.

这可以用 ActionFilters 实施。例如可以在 MvcContrib 项目code为:<一href=\"http://mvccontrib.$c$cplex.com/SourceControl/changeset/view/b7618332021c#src/MVCContrib/Filters/ModelStateToTempDataAttribute.cs\"><$c$c>ModelStateToTempDataAttribute

This can be implemented with ActionFilters. Examples can be found in the MvcContrib project code: ModelStateToTempDataAttribute

这也与其他提示在最佳做法的文章中提到一起<一个href=\"http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx\">weblogs.asp.net (好像笔者感动的博客,但我无法找到新的博客文章)。从文章:

This has also been mentioned together with other tips in a 'best practices' article on weblogs.asp.net (seems the author has moved the blog, but I couldn't find the article on the new blog). From the article:

一对这种模式的问题是,当一个验证失败或任何
  出现异常,您必须在的ModelState复制到TempData的。如果你
  正在做手工,请停止它,你可以这样做自动
  用行动过滤器,如下所示:

One of the issue with this pattern is when a validation fails or any exception occurs you have to copy the ModelState into TempData. If you are doing it manually, please stop it, you can do this automatically with Action Filters, like the following:

控制器

[AcceptVerbs(HttpVerbs.Get), OutputCache(CacheProfile = "Dashboard"), StoryListFilter, ImportModelStateFromTempData]
public ActionResult Dashboard(string userName, StoryListTab tab, OrderBy orderBy, int? page)
{
    //Other Codes
    return View();
}

[AcceptVerbs(HttpVerbs.Post), ExportModelStateToTempData]
public ActionResult Submit(string userName, string url)
{
    if (ValidateSubmit(url))
    {
        try
        {
            _storyService.Submit(userName, url);
        }
        catch (Exception e)
        {
            ModelState.AddModelError(ModelStateException, e);
        }
    }

    return Redirect(Url.Dashboard());
}

操作过滤器

public abstract class ModelStateTempDataTransfer : ActionFilterAttribute
{
    protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName;
}

public class ExportModelStateToTempData : ModelStateTempDataTransfer
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Only export when ModelState is not valid
        if (!filterContext.Controller.ViewData.ModelState.IsValid)
        {
            //Export if we are redirecting
            if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
            {
                filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState;
            }
        }

        base.OnActionExecuted(filterContext);
    }
}

public class ImportModelStateFromTempData : ModelStateTempDataTransfer
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;

        if (modelState != null)
        {
            //Only Import if we are viewing
            if (filterContext.Result is ViewResult)
            {
                filterContext.Controller.ViewData.ModelState.Merge(modelState);
            }
            else
            {
                //Otherwise remove it.
                filterContext.Controller.TempData.Remove(Key);
            }
        }

        base.OnActionExecuted(filterContext);
    }
}

这篇关于后/状态改变后MVC3模型验证的最佳实践重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆