下拉列表和编辑器模板

本文关键字:编辑器 下拉列表 | 更新日期: 2023-09-27 18:37:26

我有一个名为发票的实体,我正在扩展它以进行数据注释

   [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[发票类型] 会导致为此元素加载发票类型编辑器模板。此模板定义为

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

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

下拉列表和编辑器模板

与其"硬编码"您的状态,我会创建一个枚举或类型安全枚举。对于您的示例,我将使用后者。

对于每个必需的"状态列表",使用所需的设置创建一个单独的类:

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>