How to use data annotations for drop-down lists?

2019-02-22 00:56发布

问题:

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

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

However, if for a mobile app, there is no field label, only a drop-down list populated from the database. How would I define this in this way?

    [Required]
    [DataType(DataType.[SOME LIST TYPE???])]
    [Display(Name = "")]
    public string Continent { get; set; }

Is it better not to use this method for this?

回答1:

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.



回答2:

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)