如何使用数据注解的下拉列表?(How to use data annotations for dro

2019-06-27 03:10发布

在MVC3数据注释可用于加快UI开发和验证; 即。

    [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; }

但是,如果在移动应用中,没有字段标签,只是从数据库中填充的下拉列表。 我怎么会这样定义这个?

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

它是最好不要使用这种这种方法吗?

Answer 1:

更改您的视图模型是这样

public class RegisterViewModel
{
   //Other Properties

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

}

并在GET操作方法,设定从您的数据库中获取数据和设置您的视图模型的大洲集合属性

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);
}

在您的ViewDoThatStep.cshtml )使用

@model RegisterViewModel
@using(Html.BeginForm())
{
  @Html.ValidationSummary()

  @Html.DropDownListFor(m => m.SelectedContinent, 
               new SelectList(Model.Continents, "Value", "Text"), "Select")

   <input type="submit" />
}

现在,这会让你的下拉必填字段。



Answer 2:

如果要强制在下拉列表中使用的元素的选择[Required]您所绑定到外地属性:

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

    public IEnumerable<SelectListItem> Continents { get; set; }
}

在您的视图:

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


文章来源: How to use data annotations for drop-down lists?