检查this implementation(本福斯特)是否有效:
我经常使用它,从来没有遇到过问题。
您是否正确设置了属性? ' RestoreModelStateFromTempDataAttribute 在get 操作上和SetTempDataModelState 在您的post 操作上?
这里是需要的 4 个类(Export、Import、Transfer 和 Validate)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.IsValid 检查,所以相同(使用操作过滤器)将是:
[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 动作过滤器,你最终会得到这样的 post 动作:
[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());
}
在上一个例子中,我同时使用了ValidateModelState和ExportModelState,这是因为ValidateModelState在ActionExecuting上运行,所以它在进入方法体之前进行验证,如果绑定有一些验证错误,它会自动重定向。
然后我有另一个检查不能在数据注释中,因为它处理加载实体并查看它是否具有正确的要求(我知道这不是最好的例子,将其视为查看提供的用户名在注册时是否可用,我知道远程数据注释但不涵盖所有情况)然后我只是根据绑定以外的外部因素用我自己的错误更新ModelState。由于ExportModelState 在ActionExecuted 上运行,所以我对ModelState 的所有修改都保留在TempData 上,所以我将它们放在HttpGet 上编辑操作。
我知道所有这一切都会让我们中的一些人感到困惑,没有关于如何在 Controller / PRG 端执行 MVC 的真正好的指示。我在努力写一篇博客文章来涵盖所有场景和解决方案。这只是其中的 1%。
我希望至少我清除了 POST - GET 工作流程的几个关键点。如果这令人困惑多于帮助,请告诉我。抱歉,帖子太长了。
我还想指出,PRG 返回的 ActionResult 与返回 RedirectToRouteResult 的 PRG 之间存在一个细微的差异。
如果您在出现 ValidationError 后刷新页面 (F5),并使用 RedirectToRouteResult,则错误将不会持续存在,并且您会获得一个干净的视图,就像您第一次进入一样。使用 ActionResult ,您刷新并看到完全相同的页面,包括错误。这与 ActionResult 或 RedirectToRouteResult 返回类型无关,因为在一种情况下您总是在 POST 上重定向,而另一种情况下您只在成功 POST 上重定向。 PRG 不建议对不成功的 POST 进行盲目重定向,但有些人更喜欢在每个帖子上都进行重定向,这需要 TempData 传输。