如何在MVC3的Razor页面上使用枚举? [英] How can I use Enums on my Razor page in MVC3?

查看:145
本文介绍了如何在MVC3的Razor页面上使用枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明了一个枚举:

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)
{

}

您只需要确保您的视图是强类型的,并且已将定义Height枚举的名称空间带入范围,就可以了:

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

或像这样引用枚举:

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

}

但是要避免在需要使用此枚举的所有剃刀视图中执行此操作,在~/Views/web.config<namespaces>部分中声明它会更容易:

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>

这篇关于如何在MVC3的Razor页面上使用枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆