【问题标题】:Reference to the enum from model in Index view在索引视图中从模型中引用枚举
【发布时间】:2017-01-04 09:22:09
【问题描述】:

我在索引视图中从模型中引用我的枚举时遇到问题。 这是我的模型的代码:

public enum UnitOfMeasure {
    Item,
    Kilogram,
    Liter, }

public class Product {
    public Product() {
        ProductOccurences = new List<ProductOccurence>(); }

    [Key]
    public int ProductId { get; set; }
    public int ProductPhotoId { get; set; }
    public UnitOfMeasure? UnitOfMeasure { get; set; }
    public string ProductDescription { get; set; }
    public virtual ProductPhoto Photo { get; set; }
    public virtual ICollection<ProductOccurence> ProductOccurences { get; set; } }

在索引视图中,我有用于过滤特定结果的搜索字段。您还可以搜索 UnitOfMeasure 值(我使用 @Html.EnumDropDownListFor)——但我不能直接从我的模型中引用枚举字段——因为我的视图是强类型的:

@model IEnumerable<Models.Product>

要使用选择的值显示此字段,我使用了技巧:

@Html.EnumDropDownListFor(model => model.FirstOrDefault().UnitOfMeasure, "Select unit of measure")

但这是一个糟糕而丑陋的解决方案——默认情况下也会加载不需要的值。 在我的情况下,解决这个问题的最优雅的方法是什么?

【问题讨论】:

  • 例如,它不应与您访问ProductDescription 的方式不同。您显示的 sn-p 应该在 @foreach (var item in Model) { 之类的内部,因此您只需忽略 model 参数并使用 item,例如@Html.EnumDropDownListFor(model =&gt; item.UnitOfMeasure, "Select unit of measure")

标签: asp.net-mvc entity-framework enums


【解决方案1】:

你可以像这样使用 EnumHelper:

@Html.DropDownList("UnitOfMeasure", EnumHelper.GetSelectList(typeof(UnitOfMeasure)))

对于强类型视图,您可以这样做:

@{ // you can put the following in a back-end method and pass through ViewBag
    var selectList = Enum.GetValues(typeof(UnitOfMeasure))
                         .Cast<UnitOfMeasure>()
                         .Select(e => new SelectListItem
                             {
                                 Value = ((int)e).ToString(),
                                 Text = e.ToString()
                             });
}
@Html.DropDownListFor(m => m.UnitOfMeasure, selectList)

【讨论】:

  • 非常感谢。这正是我想要的。我选择了第一个选项,还添加了第三个参数 - 使用默认文本。
猜你喜欢
  • 1970-01-01
  • 2012-03-08
  • 2013-09-12
  • 2010-10-01
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
  • 2020-04-03
  • 2011-12-28
相关资源
最近更新 更多