asp.net-mvcasp.net-mvc-3razor

Implementing a switch statement in a CSHTML page


I'm trying to do something different. I have a view that contains an Id. Based on the value of the Id I want to change my heading that appears. Something like:

@{ switch id
   case "test": @;<h1>Test Site</h1>
   case "prod": @:<h1>Prod Site</h1>
   break;
}

I have quite a lot of case conditions so I though use of case would be best. Can anyone suggest how I can do this and get it to work? I am getting a lot of syntax errors so I think maybe it's not coded well.


Solution

  • Your switch needs to be completely enclosed in a block and it needs to be "broken" properly:

    // Use the @{ } block and put all of your code in it
    @{
        switch(id)
        {
            case "test":
                // Use the text block below to separate html elements from code
                <text>
                    <h1>Test Site</h1>
                </text>
                break;  // Always break each case
            case "prod":
                <text>
                    <h1>Prod Site</h1>
                </text>
                break;
            default:
                <text>
                    <h1>WTF Site</h1>
                </text>
                break;                   
        }
    }
    

    Because the <h1> tags are enclosed html blocks by themselves, you may not need the <text> blocks for separation. It's just my habit to include them.