How to use data annotations for dropdowns?

In MVC3, data annotations can be used to speed up development and validation of the user interface; i.e.

[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 there is no field label for the mobile application, only a drop-down list populated from the database. How would I define it this way?

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

Isn't it better to use this method for this?

+7
source share
2 answers

Change your ViewModel as follows

 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 Get Data from your database 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 View ( DoThatStep.cshtml ) use

 @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 Requested Drop field.

+8
source

If you want to apply item selection in DropDown, use the [Required] attribute in the field to which you are attached:

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

and in your opinion:

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

All Articles