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

前端 未结 3 782
一整个雨季
一整个雨季 2021-02-18 20:17

I declared an enum:

public enum HeightTypes{    Tall,    Short}

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

@if (Model.Met         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-18 20:54

    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 section in the ~/Views/web.config:

    
        
        
          
            
            
            
            
            
          
        
    
    

提交回复
热议问题