条件模型状态合并



我实现了对"在RedirectToAction中保留ModelState错误?"问题的第二个响应,该问题涉及使用两个自定义ActionFilterAttributes。我喜欢这个解决方案,它只需为需要功能的方法添加一个属性,就可以保持代码的整洁。

该解决方案在大多数情况下都能很好地工作,但我遇到了一个重复部分视图的问题。基本上,我有一个部分视图,它使用自己的模型,与父视图使用的模型分离。

我的代码的简化版本从主视图:

@for (int i = 0; i < Model.Addresses.Count; i++)
{
        address = (Address)Model.Addresses[i];
        @Html.Partial("_AddressModal", address);
}

局部视图"_AddressModal":

@model Acme.Domain.Models.Address
[...]
@Html.TextBoxFor(model => model.Address1, new { @class = "form-control" } )
[...]

当不使用自定义ActionFilterAttributes时,一切都按预期进行。每次执行Partial View时,lamba表达式(如"model=>model.Address1")都会从ModelState中提取正确的值。

问题是当我获得重定向并使用了自定义ActionFilterAttributes时。核心问题是,不仅更新了Address的一个实例的ModelState,而且部分视图生成的所有Address的ModelState都被覆盖,因此它们包含相同的值,而不是正确的实例值。

我的问题是如何修改自定义ActionFilterAttributes,使其仅更新一个受影响Address实例的ModelState,而不是所有ModelState?我希望避免向使用该属性的方法添加任何内容,以保持干净的实现。

以下是来自另一个问题的自定义ActionFilterAttributes代码:

public class SetTempDataModelStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);         
        filterContext.Controller.TempData["ModelState"] = 
           filterContext.Controller.ViewData.ModelState;
    }
}
public class RestoreModelStateFromTempDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        if (filterContext.Controller.TempData.ContainsKey("ModelState"))
        {
            filterContext.Controller.ViewData.ModelState.Merge(
                (ModelStateDictionary)filterContext.Controller.TempData["ModelState"]);
        }
    }
}

检查此实现(ben-forst)是否有效:我用得很重,从来没有遇到过问题。

您是否正确设置了属性?'RestoreModelStateFromTempDataAttributeget操作上,SetTempDataModelState在您的post操作上?

以下是所需的4个类(导出、导入、传输和验证)ModelState

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ExportModelStateToTempDataAttribute : ModelStateTempDataTransfer
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Only copy when ModelState is invalid and we're performing a Redirect (i.e. PRG)
            if (!filterContext.Controller.ViewData.ModelState.IsValid &&
                (filterContext.Result is RedirectResult || filterContext.Result is RedirectToRouteResult)) 
            {
                ExportModelStateToTempData(filterContext);
            }
            base.OnActionExecuted(filterContext);
        }
    }

 /// <summary>
    /// An Action Filter for importing ModelState from TempData.
    /// You need to decorate your GET actions with this when using the <see cref="ValidateModelStateAttribute"/>.
    /// </summary>
    /// <remarks>
    /// Useful when following the PRG (Post, Redirect, Get) pattern.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ImportModelStateFromTempDataAttribute : ModelStateTempDataTransfer
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Only copy from TempData if we are rendering a View/Partial
            if (filterContext.Result is ViewResult)
            {
                ImportModelStateFromTempData(filterContext);
            }
            else 
            {
                // remove it
                RemoveModelStateFromTempData(filterContext);
            }
            base.OnActionExecuted(filterContext);
        }
    }
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public abstract class ModelStateTempDataTransfer : ActionFilterAttribute
    {
        protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName;
        /// <summary>
        /// Exports the current ModelState to TempData (available on the next request).
        /// </summary>       
        protected static void ExportModelStateToTempData(ControllerContext context)
        {
            context.Controller.TempData[Key] = context.Controller.ViewData.ModelState;
        }
        /// <summary>
        /// Populates the current ModelState with the values in TempData
        /// </summary>
        protected static void ImportModelStateFromTempData(ControllerContext context)
        {
            var prevModelState = context.Controller.TempData[Key] as ModelStateDictionary;
            context.Controller.ViewData.ModelState.Merge(prevModelState);
        }
        /// <summary>
        /// Removes ModelState from TempData
        /// </summary>
        protected static void RemoveModelStateFromTempData(ControllerContext context)
        {
            context.Controller.TempData[Key] = null;
        }
    }
  /// <summary>
    /// An ActionFilter for automatically validating ModelState before a controller action is executed.
    /// Performs a Redirect if ModelState is invalid. Assumes the <see cref="ImportModelStateFromTempDataAttribute"/> is used on the GET action.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ValidateModelStateAttribute : ModelStateTempDataTransfer
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.Controller.ViewData.ModelState.IsValid)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    ProcessAjax(filterContext);
                }
                else
                {
                    ProcessNormal(filterContext);
                }
            }
            base.OnActionExecuting(filterContext);
        }
        protected virtual void ProcessNormal(ActionExecutingContext filterContext)
        {
            // Export ModelState to TempData so it's available on next request
            ExportModelStateToTempData(filterContext);
            // redirect back to GET action
            filterContext.Result = new RedirectToRouteResult(filterContext.RouteData.Values);
        }
        protected virtual void ProcessAjax(ActionExecutingContext filterContext)
        {
            var errors = filterContext.Controller.ViewData.ModelState.ToSerializableDictionary();
            var json = new JavaScriptSerializer().Serialize(errors);
            // send 400 status code (Bad Request)
            filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, json);
        }
    }

编辑

这是一个正常的(非作用滤波器)PRG模式:

    [HttpGet]
    public async Task<ActionResult> Edit(Guid id)
    {
        var calendarEvent = await calendarService.FindByIdAsync(id);
        if (calendarEvent == null) return this.RedirectToAction<CalendarController>(c => c.Index());
        var model = new CalendarEditViewModel(calendarEvent);
        ViewData.Model = model;
        return View();
    }
    [HttpPost]
    public async Task<ActionResult> Edit(Guid id, CalendarEventBindingModel binding)
    {
        if (!ModelState.IsValid) return await Edit(id);
        var calendarEvent = await calendarService.FindByIdAsync(id);
        if (calendarEvent != null)
        {
            CalendarEvent model = calendarService.Update(calendarEvent, binding);
            await context.SaveChangesAsync();
        }
        return this.RedirectToAction<CalendarController>(c => c.Index());
    }

使用操作筛选器(或其目的),您希望避免的是删除ModelState.is对每个操作后进行有效检查,因此(使用操作筛选器)相同:

    [HttpGet, ImportModelStateFromTempData]
    public async Task<ActionResult> Edit(Guid id)
    {
        var calendarEvent = await calendarService.FindByIdAsync(id);
        if (calendarEvent == null) return this.RedirectToAction<CalendarController>(c => c.Index());
        var model = new CalendarEditViewModel(calendarEvent);
        ViewData.Model = model;
        return View();
    }
    // ActionResult changed to RedirectToRouteResult
    [HttpPost, ValidateModelState]
    public async Task<RedirectToRouteResult> Edit(Guid id, CalendarEventBindingModel binding)
    {
        // removed ModelState.IsValid check
        var calendarEvent = await calendarService.FindByIdAsync(id);
        if (calendarEvent != null)
        {
            CalendarEvent model = calendarService.Update(calendarEvent, binding);
            await context.SaveChangesAsync();
        }
        return this.RedirectToAction<CalendarController>(c => c.Index());
    }

这里没有更多的事情发生。因此,如果你只使用ExportModelState操作过滤器,你会得到这样的后操作:

    [HttpPost, ExportModelStateToTempData]
    public async Task<RedirectToRouteResult> Edit(Guid id, CalendarEventBindingModel binding)
    {
        if (!ModelState.IsValid) return RedirectToAction("Edit", new { id });
        var calendarEvent = await calendarService.FindByIdAsync(id);
        if (calendarEvent != null)
        {
            CalendarEvent model = calendarService.Update(calendarEvent, binding);
            await context.SaveChangesAsync();
        }
        return this.RedirectToAction<CalendarController>(c => c.Index());
    }

这让我问你,你为什么一开始就为ActionFilters而烦恼?虽然我确实喜欢ValidateModelState模式(很多人不喜欢),但如果你在控制器中重定向,我真的看不到任何好处,除了一种情况,你有额外的模型状态错误,为了完整起见,让我给你举一个例子:

    [HttpPost, ValidateModelState, ExportModelStateToTempData]
    public async Task<RedirectToRouteResult> Edit(Guid id, CalendarEventBindingModel binding)
    {
        var calendarEvent = await calendarService.FindByIdAsync(id);
        if (!(calendarEvent.DateStart > DateTime.UtcNow.AddDays(7))
            && binding.DateStart != calendarEvent.DateStart)
        {
            ModelState.AddModelError("id", "Sorry, Date start cannot be updated with less than 7 days of event.");
            return RedirectToAction("Edit", new { id });
        }
        if (calendarEvent != null)
        {
            CalendarEvent model = calendarService.Update(calendarEvent, binding);
            await context.SaveChangesAsync();
        }
        return this.RedirectToAction<CalendarController>(c => c.Index());
    }

在上一个例子中,我同时使用了ValidateModelStateExportModelState,这是因为ValidateModelStateActionExecuting上运行,所以它在进入方法体之前进行验证,如果绑定有一些验证错误,它将自动重定向。然后,我有另一个检查不能在数据注释中,因为它处理加载实体并查看它是否具有正确的要求(我知道这不是最好的例子,可以认为它是查看注册时提供的用户名是否可用,我知道远程数据注释,但不涵盖所有情况),然后我只根据外部情况使用自己的错误更新ModelState除了绑定之外的其他因素。由于ExportModelStateActionExecuted上运行,所以我对ModelState的所有修改都在TempData上持久化,所以我将在HttpGet编辑操作中使用它们。

我知道所有这些都会让我们中的一些人感到困惑,对于如何在Controller/PRG端进行MVC,没有真正好的指示。我在写一篇博客文章以涵盖所有场景和解决方案时进行了认真思考。这只是其中的1%。

我希望至少我澄清了POST-GET工作流程的几个关键点。如果这让人困惑而没有帮助,请告诉我。抱歉发了这么长的邮件。

我还想注意的是,返回ActionResult的PRG与返回RedirectToRouteResult的有一个细微的差异。如果您在出现ValidationError后使用RedirectToRouteResult刷新页面(F5),则错误将不会持久存在,并且您将获得一个干净的视图,就像您第一次输入一样。使用ActionResult,您可以刷新并看到完全相同的页面,包括错误。这与ActionResult或RedirectToRouteResult返回类型无关,因为在一种情况下,您总是在POST时重定向,而在另一种情况中,您只在成功POST时重定向。PRG并不建议在不成功的POST上盲目重定向,但有些人更喜欢在每个帖子上进行重定向,这需要TempData传输。

最新更新