How to use data annotations for drop-down lists?

前端 未结 2 766
囚心锁ツ
囚心锁ツ 2021-01-12 14:20

In MVC3 data annotations can be used to speed up the UI development and validations; ie.

    [Required]
    [StringLength(100, ErrorMessage = \"The {0} must          


        
2条回答
  •  感动是毒
    2021-01-12 14:32

    If you want to enforce the selection of an element in the DropDown use the [Required] attribute on the field you are binding to:

    public class MyViewModel
    {
        [Required]
        [Display(Name = "")]
        public string Continent { get; set; }
    
        public IEnumerable Continents { get; set; }
    }
    

    and in your view:

    @Html.DropDownListFor(
        x => x.Continent, 
        Model.Continents, 
        "-- Select a continent --"
    )
    @Html.ValidationMessageFor(x => x.Continent)
    

提交回复
热议问题