2016-12-04 166 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