2016-12-04 177 views
1

我已經爲ViewModel中的Role字段設置了RequiredValidationmessage。據推測dropdownlist反映ViewModel中的Role字段。但是,當我沒有從dropdownlist中選擇任何值時,即使我已經爲該字段設置Required驗證,它也不會顯示任何錯誤。任何想法爲什麼?ASP.NET MVC ValidationMessage不顯示下拉列表

視圖模型:

public class RegisterViewModel 
{ 
    [Required] 
    [EmailAddress] 
    [Display(Name = "Email")] 
    public string Email { get; set; } 

    [Required] 
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
    [DataType(DataType.Password)] 
    [Display(Name = "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; } 

    [Required(ErrorMessage = "Please select a user type")] 
    [Display(Name = "Select user type:")] 
    public string Role { get; set; } 
} 

的觀點:

<div class="form-group"> 
    @Html.LabelFor(m => m.Role, new { @class = "col-md-2 control-label"}) 
    <div class="col-md-10"> 
     @Html.DropDownList("Role", null, "Select user type", new { @class = "form-control" }) 
     @Html.ValidationMessage("Role") 
    </div> 
</div> 
+0

您的請求是否會觸發控制器的操作,您是否可以檢查模型的狀態? – kat1330

回答

1

當您使用的DropDownList()過載你不能讓客戶端驗證時,第一個參數是IEnumerable<SelectListItem>(即當使用與SelectList相同的名稱作爲綁定的屬性)。如果您檢查了您生成的html,您將會看到<select>元素沒有生成data-val-*屬性。

如果你使用(比方說)它的工作使用

ViewBag.RoleList = new SelectList(...); 
控制器

@Html.DropDownList("Role", (IEnumerable<SelectListItem>),ViewBag.RoleList "Select user type", new { @class = "form-control" }) 

的觀點,但是因爲你有一個視圖模型(這是最好的做法),然後將SelectList的屬性添加到模型

public class RegisterViewModel 
{ 
    .... 
    [Required(ErrorMessage = "Please select a user type")] 
    [Display(Name = "Select user type:")] 
    public string Role { get; set; } 
    public IEnumerable<SelectListItem> RoleList { get; set; } 
} 

並在GET方法OD,填充在收集你傳遞模型前視圖

RegisterViewModel model = new RegisterViewModel() 
{ 
    RoleList = .... // your query to generate the SelectList 
}; 
return View(model); 

,並在視圖中,使用強類型HtmlHelper方法

@Html.DropDownListFor(m => m.Role, Model.RoleList "Select user type", new { @class = "form-control" }) 
@Html.ValidationMessageFor(m => m.Role) 

this DotNetFiddle漱口,爲何財產的結合進一步的例子並且ViewBagSelectList的名稱不應該相同。

+0

我有你的想法,但我不知道如何從數據庫上下文中填充「IEnumerable RoleList」。任何幫助表示讚賞! – Pow4Pow5

+0

好的,我已經解決了這個問題!謝謝您的回答! – Pow4Pow5