ElH*_*aix 7 user-interface razor asp.net-mvc-3
在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; }
Run Code Online (Sandbox Code Playgroud)
但是,如果对于移动应用程序,没有字段标签,则只会从数据库中填充下拉列表.我将如何以这种方式定义它?
[Required]
[DataType(DataType.[SOME LIST TYPE???])]
[Display(Name = "")]
public string Continent { get; set; }
Run Code Online (Sandbox Code Playgroud)
最好不要使用这种方法吗?
像这样更改您的ViewModel
public class RegisterViewModel
{
//Other Properties
[Required]
[Display(Name = "Continent")]
public string SelectedContinent { set; get; }
public IEnumerable<SelectListItem> Continents{ set; get; }
}
Run Code Online (Sandbox Code Playgroud)
在GETAction方法中,设置从数据库获取数据并设置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);
}
Run Code Online (Sandbox Code Playgroud)
并在你的View(DoThatStep.cshtml)中使用它
@model RegisterViewModel
@using(Html.BeginForm())
{
@Html.ValidationSummary()
@Html.DropDownListFor(m => m.SelectedContinent,
new SelectList(Model.Continents, "Value", "Text"), "Select")
<input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)
现在,这将使您的DropDown必填字段.