chuckd
chuckd

Reputation: 14530

Enum object not found with razor

The object 'YogaSpaceAccommodation' that I'm using as my type in GetEnumDescription seems to be brown and not found. Or something here isn't correct in terms of syntax.

<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 looks like this

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;
    }

Upvotes: 1

Views: 924

Answers (1)

Brad C
Brad C

Reputation: 2982

Find out which namespace your enum is in and add a using declaration at the top of the View. Say your namespace is MyApp.Data.Enums you would add:

@using MyApp.Data.Enums

to the top of the view by the @model declaration. You can also add the namespace through the web.config located in your views folder:

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

Note that when you make these changes you usually have to close and reopen the views for intellisense to catch up. You may need the namespace of the helper functions you are using.

Upvotes: 1

Related Questions