DropDownList和EditorTemplates

时间:2012-06-15 20:03:30

标签: c# .net asp.net-mvc asp.net-mvc-3

我有一个名为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; }

    }

Uhint [InvoiceType]导致为此元素加载InvoiceType编辑器模板。此模板定义为

@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)     

 }

我的程序中有很多这样的硬编码状态列表。我说硬编码是因为它们不是从数据库中提取的。是否有其他方法可以为下拉菜单创建模板?如何在模型中声明枚举并让下拉加载枚举而不必将其传递给视图模型?

1 个答案:

答案 0 :(得分:1)

我会创建一个枚举或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>