MVC ValidationMessageFor不能正常工作

我认为我有以下几点:

User Registration
@Html.LabelFor(m => m.UsrName)
@Html.TextBoxFor(m => m.UsrName) @Html.ValidationMessageFor(m => m.UsrName)
@Html.LabelFor(m => m.Pwd)
@Html.PasswordFor(m => m.Pwd) @Html.ValidationMessageFor(m => m.Pwd)
@Html.LabelFor(m => m.ReEnterPwd)
@Html.PasswordFor(m => m.ReEnterPwd) @Html.ValidationMessageFor(m => m.ReEnterPwd)
Location @Html.RadioButtonFor(m => m.Location, "Loc1") @Html.Label("Loc1")    @Html.RadioButtonFor(m => m.Location, "Loc2") @Html.Label("Loc2") @Html.ValidationMessageFor(m => m.Location)
Role @Html.RadioButtonFor(m => m.Role, "User") @Html.Label("User")    @Html.RadioButtonFor(m => m.Role, "Admin") @Html.Label("Admin") @Html.ValidationMessageFor(m => m.Role)

即使我没有填充所有字段,它仍然会进入控制器,即使它们都是必需的。 我想

  @Html.ValidationMessageFor 

应该是为了防止这种情况。

  [Required] public string Location { get; set; } [Required] public string Role { get; set; } [Required] [Display(Name = "User Name")] public string UsrName { get; set; } [Required] [StringLength(50, MinimumLength = 5, ErrorMessage = "Must have a minimum length of 5.")] public string Pwd { get; set; } [Required] [Display(Name = "Re-enter Password")] [StringLength(50, MinimumLength = 5, ErrorMessage = "Must have a minimum length of 5.")] [Compare("Pwd", ErrorMessage = "The password and re-entered password do not match.")] public string ReEnterPwd { get; set; } 

您必须在视图中包含以下脚本: