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

2020-08-09 09:55发布

问题:

I declared an enum:

public enum HeightTypes{    Tall,    Short}

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

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

But there's a problem as I get an error. Is there some way I can tell the razor page about my enum?

回答1:

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>


回答2:

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>


回答3:

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" />