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 could use ajax to post the value to the server and return the text value. Or you could pass a collection/dictionary or the enums int and name values to the view and convert it to a javascript array and search that array for the corresponding value.
In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace. It improves a program's readability, maintainability and reduces complexity.
The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.
No, it can't as this would mean that you would be able to modify existing types at runtime which you can't. Why you say you cant add values to an existing enum if the other answears are adding?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With