如何在ASP.NET Core Razor Pages中定义条件模型绑定? [英] How to define conditional model binding in ASP.NET Core Razor Pages?

查看:85
本文介绍了如何在ASP.NET Core Razor Pages中定义条件模型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ASP.NET Core Razor Pages中创建一个简单的登录表单,该表单具有电子邮件地址字段,密码字段,登录按钮和忘记密码按钮.

I'm trying to make a simple login form in ASP.NET Core Razor Pages, which has an email address field, a password field, a login button and a forgot-password button.

我想在文本字段上使用内置的客户端和服务器端验证,这样两个按钮提交都需要使用电子邮件字段,而登录按钮提交则只需要密码字段.

I want to utilize the inbuilt client-side and server-side validation on the text fields, such that the email field is required for both button submissions, but the password field is only required for login button submission.

使用 [Required] 属性装饰模型属性使它们对于所有表单发布处理程序都是必需的,而我正在寻找某种方式来通过编程或通过条件绑定模型模型属性或处理程序方法参数上的属性.

Decorating the model properties with a [Required] attribute makes them mandatory for all form post handlers, where-as I'm looking for some way to have conditional model binding, either programmatically or through an attribute on model properties or handler method parameters.

是否可以定义条件模型绑定来实现此目的,或者是否有明确的&简单的替代方法?

Is it possible to define conditional model binding to achieve this, or is there a clean & simple alternative?

推荐答案

您可以使用自定义的required属性来实现.例如,不同的按钮将触发不同的处理程序:

You can achieve that by using custom required attribute . For example , different button will trigger different handler :

<div>
    <button type="submit" asp-page-handler="Login">Login</button>

    <button type="submit" asp-page-handler="ChangePassword">login</button>
</div>

  1. 注册 IActionContextAccessor :

services.AddHttpContextAccessor();

  • 需要定制的属性:

  • Custom required attributed :

    public class MyRequiredAttribute : RequiredAttribute 
    {
        private string _handlerName;
        public MyRequiredAttribute(string handlerName)
        {
            _handlerName = handlerName;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
    
            var httpContext = validationContext.GetRequiredService<IHttpContextAccessor>().HttpContext;
    
            var handlerName = httpContext.Request.Query["handler"].ToString();
            if (handlerName.ToLower().Equals(_handlerName.ToLower()))
            {
                return base.IsValid(value, validationContext);
    
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
    

  • 应用于您的媒体资源:

  • Apply to your property :

    [BindProperty]
    [Required]
    [MinLength(6)]
    public string UserName { get; set; }
    
    [BindProperty]
    [MyRequiredAttribute("Login"), MinLength(6)]
    public string Password { get; set; }
    

  • 这篇关于如何在ASP.NET Core Razor Pages中定义条件模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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