簡體   English   中英

MVC ValidationMessageFor不能正常工作

[英]MVC ValidationMessageFor not working properly

我認為我有以下幾點:

     <fieldset>
        <legend>User Registration</legend>            
        <div class="editor-label">
            @Html.LabelFor(m => m.UsrName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.UsrName)
            @Html.ValidationMessageFor(m => m.UsrName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(m => m.Pwd)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(m => m.Pwd)
            @Html.ValidationMessageFor(m => m.Pwd)
        </div>
        <div class="editor-label">
            @Html.LabelFor(m => m.ReEnterPwd)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(m => m.ReEnterPwd)
            @Html.ValidationMessageFor(m => m.ReEnterPwd)
        </div>            
       <fieldset>
         <legend>Location</legend>
           <span id="locationDiv"> 
           @Html.RadioButtonFor(m => m.Location, "Loc1")  @Html.Label("Loc1")
           &nbsp;&nbsp; 
           </span>
           @Html.RadioButtonFor(m => m.Location, "Loc2") @Html.Label("Loc2")               
           @Html.ValidationMessageFor(m => m.Location)
        </fieldset>         

         <fieldset>
         <legend>Role</legend>
            @Html.RadioButtonFor(m => m.Role, "User") @Html.Label("User")
           &nbsp;&nbsp; @Html.RadioButtonFor(m => m.Role, "Admin") @Html.Label("Admin")
            @Html.ValidationMessageFor(m => m.Role)
         </fieldset>  

        <p>
            <input type="submit" value="Register User" />
        </p> 
    </fieldset>

即使我沒有填充所有字段,它仍然會進入控制器,即使它們都是必需的。 我想

    @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; }

您必須在視圖中包含以下腳本:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

我必須在腳本部分的視圖底部包含JQuery Validation軟件包。

我注意到在登錄和身份驗證的所有烘焙視圖中都存在這種情況,但需要手動添加到自定義視圖中。

    @section scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM