在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; }
最好不要使用这种方法吗?
解决方法
像这样更改您的viewmodel
public class Registerviewmodel { //Other Properties [required] [Display(Name = "Continent")] public string SelectedContinent { set; get; } public IEnumerable<SelectListItem> Continents{ set; get; } }
并在您的GET Action方法中,设置从数据库获取数据并设置viewmodel的Continents Collection属性
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); }
并在您的视图(DoThatStep.cshtml)中使用此
@model Registerviewmodel @using(Html.BeginForm()) { @Html.ValidationSummary() @Html.DropDownListFor(m => m.SelectedContinent,new SelectList(Model.Continents,"Value","Text"),"Select") <input type="submit" /> }
现在,这将使您的DropDown必填字段.