how to implement switch case in Razor (.cshtml)?


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


Asked by:- bhanu
1
: 11982 At:- 11/3/2017 3:58:44 PM
razor C# razor syntax select case switch in mvc view switch case in razor







2 Answers
profileImage Answered by:- vikas_jk

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.

2
At:- 11/4/2017 12:03:38 PM
well, good answer, helped me today 0
By : pika - at :- 12/14/2017 1:37:13 PM


profileImage Answered by:- bhanu

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.

0
At:- 7/13/2021 4:55:36 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use