ASP.NET MVC ValidationMessage不显示下拉列表
问题描述:
我已经为ViewModel
中的Role
字段设置了Required
Validationmessage
。据推测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>
答
当您使用的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漱口,为何财产的结合进一步的例子并且ViewBag
的SelectList
的名称不应该相同。
您的请求是否会触发控制器的操作,您是否可以检查模型的状态? – kat1330