Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 509
Marianne Avatar asked Sep 08 '11 12:09

Marianne


People also ask

What is Cshtml page?

A CSHTML file is a C# HTML webpage file used by Razor, an ASP.NET view engine that generates webpages. It is similar to a standard ASP.NET webpage (. ASP or . ASPX file) but uses slightly different syntax.

How do you call a method in Razor pages?

Razor pages have handler-methods which are HTTP verbs. So to call a method from your page you need to put On followed by the http verb you want then your method name . And in your view pass the name to the asp-page-handler without the OnPost or OnGet prefix or Async suffix.

Is Cshtml a Razor?

cshtml files are razorpages or MVC views, they does not contain any C#-written client-side code. If you wan to do so, you must use JavaScript. However, a . razor file, also know as a Razor component, can have C# written in it and run on client's browser.

What can the @page directive do in a Razor page?

@page makes the file into an MVC action, which means that it handles requests directly, without going through a controller. @page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs. Razor Pages file names have a .


1 Answers

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.

like image 125
Joel Etherton Avatar answered Oct 04 '22 09:10

Joel Etherton