简体   繁体   中英

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

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?

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>

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM