Hadi Sharifi
Hadi Sharifi

Reputation: 1527

Use switch case in MVC view

In MVC view I have a 'for' command that in each value I want to write specified tag.

I show you a simple case here:

@for (var i = 0; i < 4; i++)
{
    <div>
        @(switch (i)
        {
            case 0: ??? //write "<div>Custom Value 1</div>"
                     break;
            case 1: ??? //write "<span>Custom Value 2</span>"
                     break;
        })
    </div>
}

I use MVC4 Razor view.

Thanks for your time in advance.

Upvotes: 14

Views: 31542

Answers (4)

fatderda
fatderda

Reputation: 81

As an addition to the accepted answer, if you're dealing with literals (for example if you want to dynamically set a class) you can't just write them in the case statement.

You can use @: to print them. Example:

<div class="alert @switch(state){
   case State.OK:
   @:alert-success
   case State.ERROR:
   @:alert-danger
   case State.RUNNING:
   @:alert-info
}">...</div>

Upvotes: 0

Beginner
Beginner

Reputation: 92

Switch (condition)
{
Case value or result :
Statement 
Break;
Default:

}

Upvotes: 1

Abdur Rahim
Abdur Rahim

Reputation: 4031

This should work.

@for (var i = 0; i < 4; i++)
{
    <div>
        @switch (i)
        {
            case 0: 
                     <div>Custom Value 1</div>
                     break;
            case 1: 
                     <span>Custom Value 2</span>
                     break;
        }
    </div>
}

Upvotes: 2

user3206982
user3206982

Reputation: 603

It's simple, you use your code same as this, It's works fine.

@for (var i = 0; i < 4; i++)
{
    <div>
        @switch (i)
        {
            case 0: 
                     <div>Custom Value 1</div>
                     break;
            case 1: 
                     <span>Custom Value 2</span>
                     break;
        }
    </div>
}

Upvotes: 24

Related Questions