.Net Core 显示模型验证与验证过滤器 [英] .Net Core display model validation with validation filter

查看:32
本文介绍了.Net Core 显示模型验证与验证过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个基本的 .Net Core Mvc 应用程序,我想为我的所有操作自动设置 ModelState.IsValid 这里是验证过滤器的代码

I created a basic .Net Core Mvc application and I want to automatically set ModelState.IsValid for all my action here is the code of Validation Filter

public class ValidationFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (!context.ModelState.IsValid)
        {
        }

        await next();
    }
}

这是我的操作代码

[HttpPost]
    public IActionResult AddUser(LoginRequestViewModel loginRequestViewModel)
    {
        return View(loginRequestViewModel);
    }

我应该返回什么来显示 asp-validation-for 中的错误?不使用任何 javascript 代码..

What should I return to display the errors in the asp-validation-for? Without using any javascript code..

推荐答案

根据你的代码测试,可以实现全局过滤.需要在 startup.cs 中使 ValidationFilter 成为全局过滤器.

According to the test of your code, global filtering can be achieved. Need to make ValidationFilter a global filter in startup.cs.

services.AddControllersWithViews(option=>
            {
                option.Filters.Add(new ValidationFilter());
            });

然后,创建一个模型.

 public class LoginRequestViewModel
    {
        [MinLength(3)]
        public string username { get; set; }
        public string email { get; set; }
}

在 ValidationFilter 中定义错误消息.

Define error messages in ValidationFilter.

public class ValidationFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (!context.ModelState.IsValid)
        {
            //Customize your error message
            string messages = string.Join("; ",context.ModelState.Values
                     .SelectMany(x => x.Errors)
                     .Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
            context.RouteData.Values.Add("mes", messages);
        }
        
        await next();
    }
}

在行动中,获取 RouteData.

In action, get RouteData.

[HttpPost]
        public IActionResult AddUser(LoginRequestViewModel loginRequestViewModel)
        {
            ViewData["error"]= RouteData.Values["mes"];
            return View(loginRequestViewModel);
        }

创建 AddUser.cshtml 并使用表单.

Create AddUser.cshtml and use form.

 @model solution921.Controllers.LoginRequestViewModel
<form action="/home/AddUser" method="post">
@ViewData["error"]
    <input type="text" name="username" value="" />
    <span asp-validation-for="username"></span>
    <input type="text" name="email" value="" />
    <input type="submit" name="" value="sub" />
</form>

它可以返回正确的验证.

It can return correct validation.

这篇关于.Net Core 显示模型验证与验证过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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