asp-validation-for triggering on get .net core
我有一个.NET Core应用程序,一旦从get返回页面,就会触发验证。我有一个视图模型,我不确定为什么收到响应后就已经触发了验证。
这是我的模型和标记
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System.ComponentModel.DataAnnotations; namespace MusicianProject.Models.ViewModels { public class RegisterViewModel { [Required(ErrorMessage ="First name is required.")] [Display(Name ="First Name")] [StringLength(25, ErrorMessage ="First name must be less than 25 characters.")] public string FirstName { get; set; } [Required(ErrorMessage ="Last name is required")] [Display(Name ="Last Name")] [StringLength(50, ErrorMessage ="Last name must be less than 50 characters.")] public string LastName { get; set; } [Required] [EmailAddress] [Display(Name ="Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage ="The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name ="Password")] public string Password { get; set; } [Required] [DataType(DataType.Password)] [Display(Name ="Confirm password")] [Compare("Password", ErrorMessage ="The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } } |
这是返回的寄存器视图。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | @model MusicianProject.Models.ViewModels.RegisterViewModel <form asp-controller="Account" asp-action="Register" method="post"> <label asp-for="FirstName"></label> <input class="form-control" type="text" asp-for="FirstName" /> <span asp-validation-for="FirstName">First name is required.</span> <label asp-for="LastName"></label> <input class="form-control" asp-for="LastName" /> <span asp-validation-for="LastName">Last name is required.</span> <label asp-for="Email"></label> <input class="form-control" type="text" asp-for="Email" /> <span asp-validation-for="Email">Email is required.</span> <label asp-for="Password"></label> <input asp-for="Password" type="password" id="password" class="form-control" /> <span asp-validation-for="Password">Password is required.</span> <label asp-for="ConfirmPassword"></label> <input asp-for="ConfirmPassword" type="password" id="confirm-password" class="form-control" /> <span asp-validation-for="ConfirmPassword">Confirm password is required</span> <button class="btn btn-default">Sign up!</button> <button class="btn btn-danger">Cancel</button> </form> |
我有两种注册方法,post和get。这就是我所拥有的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | [HttpGet] public IActionResult Register() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Register(RegisterViewModel rvm) { if (ModelState.IsValid) { return RedirectToAction("Index","Home"); } return View(); } |
当我在浏览器中导航到该路线时,这就是我得到的。
只需删除视图中
当出现验证错误时,标签助手将为您注入文本,具体取决于注释的设置。您现在拥有的方式将强制打印这些消息。