How can I use Enums on my Razor page in MVC3?

前端 未结 3 768
一整个雨季
一整个雨季 2021-02-18 20:17

I declared an enum:

public enum HeightTypes{    Tall,    Short}

Now I want to use it on my razor page like this:

@if (Model.Met         


        
相关标签:
3条回答
  • 2021-02-18 20:51

    You aren't specific about the exception, so I'm guessing this is a namespace issue. Add

    @using The.Namespace.Of.Your.Enum;
    

    at the top. You can also specify namespaces to add automatically in /Views/web.config if you are going to use that namespace a lot:

    <system.web.webPages.razor>
        ...
        <pages ...>
            <namespaces>
                <add namespace="System.Web" />
                ...
                <add namespace="The.Namespace.Of.Your.Enum" />
    
    0 讨论(0)
  • 2021-02-18 20:54

    You have an error in your enum declaration (remove the trailing ;):

    public enum HeightTypes { Short = 0, Tall = 1 }
    

    then the following test should work:

    @if (Model.Meta.Height == HeightTypes.Tall)
    {
    
    }
    

    you just have to make sure that your view is strongly typed and that you have brought into scope the namespace in which the Height enum is defined:

    @using SomeAppName.Models
    @model SomeViewModel
    

    or reference the enum like this:

    @if (Model.Meta.Height == SomeAppName.Models.HeightTypes.Tall)
    {
    
    }
    

    But to avoid doing this in all your razor views that require using this enum, it is easier to declare it in the <namespaces> section in the ~/Views/web.config:

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="SomeAppName.Models" />
          </namespaces>
        </pages>
    </system.web.webPages.razor>
    
    0 讨论(0)
  • 2021-02-18 21:08

    Just do give a start-to-finish example:

    C# CS Page

    namespace MyProject.Enums
    {
        public enum CurveBasis
        {
            Aggregates,
            Premium
        }
    }
    

    Razor View

    @using MyProject.Enums
    
    <select id="dlCurveBasis">
        <option value="@CurveBasis.Aggregates">Aggregates</option>
        <option value="@CurveBasis.Premium">Premium</option>
    </select>
    
    0 讨论(0)
提交回复
热议问题