How to use data annotations for drop-down lists?

前端 未结 2 749
囚心锁ツ
囚心锁ツ 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<SelectListItem> Continents { get; set; }
    }
    

    and in your view:

    @Html.DropDownListFor(
        x => x.Continent, 
        Model.Continents, 
        "-- Select a continent --"
    )
    @Html.ValidationMessageFor(x => x.Continent)
    
    0 讨论(0)
  • 2021-01-12 14:37

    Change your ViewModel like this

    public class RegisterViewModel
    {
       //Other Properties
    
       [Required]
       [Display(Name = "Continent")]
       public string SelectedContinent { set; get; }
       public IEnumerable<SelectListItem> Continents{ set; get; }
    
    }
    

    and in your GET Action method, Set the Get the Data from your DB and set the Continents Collection property of your ViewModel

    public ActionResult DoThatStep()
    {
      var vm=new RegisterViewModel();
      //The below code is hardcoded for demo. you may replace with DB data.
      vm.Continents= new[]
      {
        new SelectListItem { Value = "1", Text = "Prodcer A" },
        new SelectListItem { Value = "2", Text = "Prodcer B" },
        new SelectListItem { Value = "3", Text = "Prodcer C" }
      }; 
      return View(vm);
    }
    

    and in your View (DoThatStep.cshtml) use this

    @model RegisterViewModel
    @using(Html.BeginForm())
    {
      @Html.ValidationSummary()
    
      @Html.DropDownListFor(m => m.SelectedContinent, 
                   new SelectList(Model.Continents, "Value", "Text"), "Select")
    
       <input type="submit" />
    }
    

    Now this will make your DropDown Required field.

    0 讨论(0)
提交回复
热议问题