gpt4 book ai didi

asp.net-mvc-3 - 后/状态更改后 MVC3 模型验证最佳实践重定向

转载 作者:行者123 更新时间:2023-12-03 04:45:18 24 4
gpt4 key购买 nike

鉴于网络应用程序应始终在 POST(或任何更改服务器端状态的不可重复请求)后重定向...

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

最佳答案

通常,您仅在成功发布后进行重定向(没有模型验证错误),否则您将发回带有验证错误消息的页面。

PRG 中的重定向模式可以防止重复发布,因此发回同一页面(+错误消息)不会有什么坏处,因为发布没有成功,并且除非进行某些更改以使验证通过,否则不会成功。

编辑:

您似乎正在寻找将 ModelState 传递给下一个(重定向的)请求。这可以通过使用 TempData 存储 ModelState 直到下一个请求来完成。仅供引用,TempData 使用 Session。

这可以通过 ActionFilters 来实现。示例可以在 MvcContrib 中找到。项目代码:ModelStateToTempDataAttribute

在关于 weblogs.asp.net 的“最佳实践”文章中也提到了这一点以及其他提示。 (好像作者已经搬了博客,但我在新博客上找不到这篇文章)。摘自文章:

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:

Controller

[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());
}

Action 过滤器

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);
}
}

关于asp.net-mvc-3 - 后/状态更改后 MVC3 模型验证最佳实践重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7940939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com