我正在尝试创建一个MVC页面,该页面将提示用户使用复选框确认3个操作之一。我的模型看起来像:
public class InstallViewModel
{
[Display(Name = "Upgrade database")]
[IsTrueAttribute(ErrorMessage = "Please confirm that you wish to perform the upgrade")]
public bool Upgrade { get; set; }
[Display(Name = "Create database")]
[IsTrueAttribute(ErrorMessage = "Please confirm that you wish to create the database")]
public bool Create { get; set; }
[Display(Name = "Delete database")]
[IsTrueAttribute(ErrorMessage = "Please confirm that you wish to delete the database")]
public bool Create { get; set; }
public String Database { get; set; }
public String DataSource { get; set; }
}
在我看来,当ViewBag指示提示他们使用@Html.CheckBoxFor(m => m.Create)
操作时,我正在使用Create
。我还必须使用@Html.HiddenFor(m => m.Upgrade)
进行非创建操作。
这看起来非常草率,并不适合新的操作(假设我想添加备份)理想情况下我希望有一个枚举(升级/创建/删除)但是如果我这样做,我将失去为操作定制DisplayName和ErrorMesssage的好处。我认为我让它变得比它需要的复杂得多。
答案 0 :(得分:0)
您可以定义类似
的枚举public enum ProductType
{
A= 1,
B= 2,
C= 3
}
并在您的模型中
public class Product
{
public string Title { get; set; }
[Display(Name = "ProductType ")]
[Required(ErrorMessage = "select product type")]
public ProductType? ProductType { get; set; }
public IEnumerable<SelectListItem> ProductTypes
{
get
{
var types =
from l in Enum.GetValues(typeof(ProductType)).Cast<ProductType>();
return new SelectList(types, "ID", "Name", this.ProductType);
}
}
}
最终视野
@Html.DropDownListFor(model => model.ProductType,Model.ProductTypes)