[英]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:现在我想在我的 razor 页面上使用它,如下所示:
@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?有什么方法可以告诉 razor 页面关于我的枚举?
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:您只需要确保您的视图是强类型的,并且您已将定义高度枚举的命名空间带入 scope:
@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
:但是为了避免在所有需要使用此枚举的 razor 视图中执行此操作,在~/Views/web.config
的<namespaces>
部分中声明它更容易:
<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 C# CS页面
namespace MyProject.Enums
{
public enum CurveBasis
{
Aggregates,
Premium
}
}
Razor View Razor 查看
@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:如果您要经常使用该命名空间,您还可以在/Views/web.config
中指定要自动添加的命名空间:
<system.web.webPages.razor>
...
<pages ...>
<namespaces>
<add namespace="System.Web" />
...
<add namespace="The.Namespace.Of.Your.Enum" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.