使用只读输入属性和[必需]数据注释进行验证错误

时间:2017-06-26 17:38:13

标签: c# asp.net-core

正如我们所知,当您使用var str: String = ... 项目模板创建ASP.NET Core appp时,它会创建一个默认的Individual User Authentication视图。在ResetPassword.cshtml中,我需要将登录的用户名输入标记设置为View。但这样做会引发以下验证错误。如果我没有成功readonly,则以下屏幕成功允许用户更改密码。

问题:为什么表单上的以下验证错误会提交 - 当UserName输入标记设置为readonly时?我知道如果输入标记被禁用,那么表单提交不会提交输入标记的值(也由readonly here解释)。 @AdamBellaire中的[Required]注释似乎与输入标记的readonly属性存在冲突。

enter image description here

public string UserName { get; set; }

更新

public class ResetPasswordViewModel { [Required] public string UserName { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } :[这是VS2017创建的默认视图。只有更改是我在下面的输入标记中添加了ResetPassword.cshtml属性]

readonly

1 个答案:

答案 0 :(得分:0)

在这种情况下,期望视图中的@User.Identity.Name绑定到视图模型中的UserName是没有意义的。

似乎IDE生成的代码是错误的。也许是某个混乱的脚手架模板,谁知道呢。

您需要将asp-for更改为等于UserName。见下文。

<input asp-for="UserName" class="form-control" readonly />

很高兴这有帮助!

相关问题