c# – 如何在ASP.NET MVC 6中继续使用ModelState和RedirectToAction?

前端之家收集整理的这篇文章主要介绍了c# – 如何在ASP.NET MVC 6中继续使用ModelState和RedirectToAction?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个删除对象的方法.删除不属于视图,并且是“EditReport”中的“删除”按钮.成功删除“报告”上的重定向后.
[HttpPost]
[Route("{reportId:int}")]
[ValidateAntiForgeryToken]
public IActionResult DeleteReport(int reportId)
{
    var success = _reportService.DeleteReportControl(reportId);
    if (success == false)
    {
        ModelState.AddModelError("Error","Messages");
        return RedirectToAction("EditReport");
    }
    ModelState.AddModelError("OK","Messages");
    return RedirectToAction("Report");
}

在ASP.NET MVC 5中,我使用以下属性方法之间保存ModelState.我从这里开始:https://stackoverflow.com/a/12024227/3878213

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

但是在ASP.NET MVC 6 RC 1(ASP.NET Core 1.0)中,此代码不起作用.

filterContext.Controller中的错误不包含TempData和ViewData的定义.

解决方法

感谢 answer,我意识到需要创建自己的代码ASP.NET Core 1.0(完整的.NET Framework 4.6.2)
public class SetTempDataModelStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        var controller = filterContext.Controller as Controller;
        var modelState = controller?.ViewData.ModelState;
        if (modelState != null)
        {
            var listError = modelState.Where(x => x.Value.Errors.Any())
                .ToDictionary(m => m.Key,m => m.Value.Errors
                .Select(s => s.ErrorMessage)
                .FirstOrDefault(s => s != null));
            controller.TempData["ModelState"] = JsonConvert.SerializeObject(listError);
        }
    }
}
public class RestoreModelStateFromTempDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        var controller = filterContext.Controller as Controller;
        var tempData = controller?.TempData?.Keys;
        if (controller != null && tempData != null)
        {
            if (tempData.Contains("ModelState"))
            {
                var modelStateString = controller.TempData["ModelState"].ToString();
                var listError = JsonConvert.DeserializeObject<Dictionary<string,string>>(modelStateString);
                var modelState = new ModelStateDictionary();
                foreach (var item in listError)
                {
                    modelState.AddModelError(item.Key,item.Value ?? "");
                }

                controller.ViewData.ModelState.Merge(modelState);
            }
        }
    }
}

代码的非同步版本ASP.NET Core 1.0(完整的.NET Framework 4.6.2)

public class SetTempDataModelStateAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext,ActionExecutionDelegate next)
        {
            await base.OnActionExecutionAsync(filterContext,next);

            var controller = filterContext.Controller as Controller;
            var modelState = controller?.ViewData.ModelState;
            if (modelState != null)
            {
                var listError = modelState.Where(x => x.Value.Errors.Any())
                    .ToDictionary(m => m.Key,m => m.Value.Errors
                    .Select(s => s.ErrorMessage)
                    .FirstOrDefault(s => s != null));
                var listErrorJson = await Task.Run(() => JsonConvert.SerializeObject(listError));
                controller.TempData["ModelState"] = listErrorJson;
            }
            await next();
        }
    }
public class RestoreModelStateFromTempDataAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext,next);

            var controller = filterContext.Controller as Controller;
            var tempData = controller?.TempData?.Keys;
            if (controller != null && tempData != null)
            {
                if (tempData.Contains("ModelState"))
                {
                    var modelStateString = controller.TempData["ModelState"].ToString();
                    var listError = await Task.Run(() => 
                        JsonConvert.DeserializeObject<Dictionary<string,string>>(modelStateString));
                    var modelState = new ModelStateDictionary();
                    foreach (var item in listError)
                    {
                        modelState.AddModelError(item.Key,item.Value ?? "");
                    }

                    controller.ViewData.ModelState.Merge(modelState);
                }
            }
            await next();
        }
    }
原文链接:https://www.f2er.com/csharp/243064.html

猜你在找的C#相关文章