如何使用数据注解的下拉列表? [英] How to use data annotations for drop-down lists?
本文介绍了如何使用数据注解的下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在MVC3数据注释可用于加快UI开发和验证;即
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?
推荐答案
更改您的视图模型像这样
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; }
}
和在 GET
Action方法,将您的数据库获取数据和设置您的视图模型的大洲集合属性。
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);
}
和在查看
( DoThatStep.cshtml
)使用
@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.
这篇关于如何使用数据注解的下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文