我有一个名为Invoice的实体,我正在为数据注释扩展它
[MetadataType(typeof(InvoiceMetadata))]
public partial class Invoice
{
// Note this class has nothing in it. It's just here to add the class-level attribute.
}
public class InvoiceMetadata
{
// Name the field the same as EF named the property - "FirstName" for example.
// Also, the type needs to match. Basically just redeclare it.
// Note that this is a field. I think it can be a property too, but fields definitely should work.
[HiddenInput]
public int ID { get; set; }
[Required]
[UIHint("InvoiceType")]
[Display(Name = "Invoice Type")]
public string Status { get; set; }
[DisplayFormat(NullDisplayText = "(null value)")]
public Supplier Supplier { get; set; }
}UhintInvoiceType会导致为此InvoiceType模板加载element.This编辑器模板,定义如下
@model System.String
@{
IDictionary<string, string> myDictionary = new Dictionary<string, string> {
{ "N", "New" }
, { "A", "Approved" },
{"H","On Hold"}
};
SelectList projecttypes= new SelectList(myDictionary,"Key","Value");
@Html.DropDownListFor(model=>model,projecttypes)
}我的程序中有许多这样的硬编码状态列表,我之所以说硬编码,是因为它们不是从数据库中获取的。有没有其他方法可以为下拉菜单创建模板?如何在模型中声明枚举,并让下拉菜单加载枚举,而不必通过视图模型?
发布于 2012-06-16 05:39:28
我不会对状态进行“硬编码”,而是创建一个Enum或一个Type Safe Enum。对于您的示例,我将使用后者。
对于每个所需的“状态列表”,使用所需的设置创建一个单独的类:
public sealed class Status
{
private readonly string _name;
private readonly string _value;
public static readonly Status New = new Status("N", "New");
public static readonly Status Approved = new Status("A", "Approved");
public static readonly Status OnHold = new Status("H", "On Hold");
private Status(string value, string name)
{
_name = name;
_value = value;
}
public string GetValue()
{
return _value;
}
public override string ToString()
{
return _name;
}
}利用反射,您现在可以获取该类的字段来创建所需的下拉列表。创建一个扩展方法或助手类对您的项目是有好处的:
var type = typeof(Status);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
Dictionary<string, string> dictionary = fields.ToDictionary(
kvp => ((Status)kvp.GetValue(kvp)).GetValue(),
kvp => kvp.GetValue(kvp).ToString()
);您现在可以创建选择列表,就像您当前所做的那样:
var list = new SelectList(dictionary,"Key","Value");这将创建一个包含以下html的下拉列表:
<select>
<option value="N">New</option>
<option value="A">Approved</option>
<option value="H">On Hold</option>
</select>https://stackoverflow.com/questions/11057469
复制相似问题