ASP.NET Core 3 Razor Page DataAnnotation Compare属性返回“找不到名为<n>的属性”

时间:2019-11-18 12:30:08

标签: asp.net-core razor-pages asp.net-core-3.0

我有一个ASP.Net Core 3剃刀页面,这是一个非常简单的重置密码表单,它使用“比较数据注释”来验证两个输入是否相同,但是,它似乎不起作用。必需的批注将触发确定,但是“比较”始终返回ModelState.Valid == false和“找不到名为Password的属性”。作为错误消息。

模型是

        [BindProperty]
        [Required(ErrorMessage = "Password is required.")]
        public string Password { get; set; }

        [BindProperty]
        [Required(ErrorMessage = "Password is required.")]
        [Compare(nameof(Password), ErrorMessage = "Passwords don't match")]
        public string ConfirmPassword { get; set; }

而cshtml是

    <form method="Post">
        <label>New Password</label>
        <input asp-for="Password" type="Password" >
        <span asp-validation-for="Password" class="text-danger"></span>

        <label>Confirm Password</label>
        <input asp-for="ConfirmPassword" type="Password" >
        <span asp-validation-for="ConfirmPassword" class="text-danger"></span>

        <button type="Submit">Reset Password</button>
    </form>

我已经将代码配对到了最低限度,似乎看不出问题出在哪里...

1 个答案:

答案 0 :(得分:0)

感谢Kirk Larkin向我指出了详细说明此问题的github问题。我决定创建一个嵌套的viewmodel类来包含属性。现在,“比较”注释可以正常工作。

嵌套的类看起来像这样...

    WindowInteropHelper windowInteropHelper = new WindowInteropHelper(Application.Current.MainWindow);
    Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);

现在网页看起来像这样...

        [BindProperty]
        public ViewModel viewModel { get; set; }
        public class ViewModel {
            [Required(ErrorMessage = "Password is required.")]
            public string Password { get; set; }

            [Required(ErrorMessage = "Confirmation Password is required.")]
            [Compare(nameof(Password), ErrorMessage = "Passwords don't match.")]
            public string ConfirmPassword { get; set; }
        }