【问题标题】:Enum object not found with razor用剃刀找不到枚举对象
【发布时间】:2015-04-25 20:11:24
【问题描述】:

我在 GetEnumDescription 中用作我的类型的对象“YogaSpaceAccommodation”似乎是棕色的并且找不到。或者这里的某些东西在语法上是不正确的。

<div id="AccomodationTypeSelector">
  <select class="form-control" id="SpaceAccommodation" name="YogaSpaceAccommodation">
    <option id="default">0</option>
    @{ 
        var accomodationValues = Enum.GetValues(typeof(YogaSpaceAccommodation)); 
        foreach (var value in accomodationValues) 
        { 
             var index = (int)@value; var description = @EnumHelper.GetEnumDescription
                       <YogaSpaceAccommodation>(@index.ToString()); 
        } 
     }
  </select>
</div>

EnumDescription 看起来像这样

public static string GetEnumDescription<T>(string value)
    {
        Type type = typeof(T);
        var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

        if (name == null)
        {
            return string.Empty;
        }
        var field = type.GetField(name);
        var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
    }

【问题讨论】:

标签: asp.net-mvc razor enums


【解决方案1】:

找出您的枚举所在的命名空间,并在视图顶部添加 using 声明。假设您的命名空间是 MyApp.Data.Enums,您将添加:

@using MyApp.Data.Enums

@model 声明到视图的顶部。您还可以通过位于您的视图文件夹中的 web.config 添加命名空间:

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="MyApp.Data.Enums" />
    </namespaces>
  </pages>
</system.web.webPages.razor>

请注意,当您进行这些更改时,您通常必须关闭并重新打开视图才能使智能感知赶上。您可能需要正在使用的辅助函数的命名空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2020-02-19
    • 2023-04-07
    • 1970-01-01
    • 2015-08-14
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多