I need to implement switch case in Razor C# page as if-else would not be a good idea, because it will create too many conditions, so i thought to create Switch case instead, here is my current code, but it throwing syntax error
@{
switch (quote.QuoteServiceId)
case 1: "<h1>Bonded</h1>"
case 2: "<h1>Cable</h1>"
break;
}
Any help is appreciated, thanks
You can implement Switch case in your razor view (.cshtml ) page as below
// Use @ symbol or palce code inside @ block
@{
var ServiceName ="";
switch (quote.QuoteServiceId) {
case 1:
ServiceName = "Case 1";
break; // Always break each case
case 2:
ServiceName = "Case 2";
break;
case 3:
ServiceName = "Case 3";
break;
default:
ServiceName = "Default Case value";
break;
}
}
Remember to place inside @ Symbol in your razor code.
Above answer works as needed, but if you want, you can also use below switch code in Razor C#
@switch (yourId)
{
case "New": <h1>New Site</h1>
break;
case "Old": <h1>Old Site</h1>
break;
}
Basically, you don't need to enclose complete code inside @{}
symbol. Above ways also works for swicth case only.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly