1

我有一个名为 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 Editor Template。此模板定义为

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

 }

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

4

1 回答 1

1

而不是“硬编码”你的状态,我会创建一个 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>
于 2012-06-15T21:39:27.617 回答