ASP.NET MVC 3 and validation attribute for dropdownlist with default value of 0

て烟熏妆下的殇ゞ 提交于 2019-12-11 19:54:37

问题


What is the best way to throw a required validation error using a validation attribute with a dropdownlist that has a default value of 0? If the value is 0, or the default value, I want the attribute to throw the error for my model.


回答1:


you can provide the option label Docs that will set the selected value to 0 if not specified other wise like @Iridio menttioned in his answer, anotate the view model property with [Required]

public class MyVieWModel
 {
   [Required]
   public int MyValue { get;set;}
   public SelectList MyValues {get;set;}
 }

and in the view

@Html.DropDownListFor(x=>x.MyValue,Model.MyValues,"-- Select --")



回答2:


Use a RequiredAttribute on your ValueId

something like this

 public class MyVieWModel
 {
   [Required]
   public int MyValue { get;set;}
   public SelectList MyValues {get;set;}
 }


来源:https://stackoverflow.com/questions/9980939/asp-net-mvc-3-and-validation-attribute-for-dropdownlist-with-default-value-of-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!