Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

proper razor syntax for switch statement inside foreach

I am having a heck of a time trying to find the proper syntax for creating a switch statement inside a foreach loop on my mvc view page.

Here is the latest attempt (after many others) I have so far but the the Razor engine won't accept it. Here the error is right at the @foreach and indicates it is missing a closing }

@foreach (var item in Model) {

    String s = item.RegistrationStatus.ToString();

    // Make sure this mirrors values in RegistrationStatus enum!
    switch (s)
    {
        case "New": 
            <tr class='info'>
                break;

        case "Arrived": 
            <tr class='success'>
            break;

        default:
            <tr>

    }


......

}
like image 870
ChiliYago Avatar asked Mar 07 '13 22:03

ChiliYago


2 Answers

You can do as Justin suggests, something in the way of this:

@foreach (var item in Model) {

    String s = item.RegistrationStatus.ToString();

    // Make sure this mirrors values in RegistrationStatus enum!
    switch (s)
    {
        case "New":
            @:<tr class='info'>
            break;

        case "Arrived":
            @:<tr class='success'>
            break;

        default:
            @:<tr>
            break;
    }

    ......
}

But, if you're running MVC4 with Razor V2, you could as easily use a helper method (or regular method) instead:

public static class MyHelperExtensions
{
    public static string GetCssClass(this HtmlHelper helper, RegistrationStatus status)
    {
        // Make sure this mirrors values in RegistrationStatus enum!
        switch (status)
        {
            case RegistrationStatus.New:
                return "info";

            case RegistrationStatus.Arrived:
                return "success";

            default:
                return null; // Return null so that the attribute won't render.
        }
    }
}

And then use it like so:

@foreach (var item in Model)
{    
    <tr class='@Html.GetCssClass(item.RegistrationStatus)'>

    .....
}

This is a bit more readable and easier to maintain. If the GetCssClass() method returns null then Razor V2 won't even render the attribute (in this case class=).

like image 84
Mario S Avatar answered Oct 21 '22 01:10

Mario S


You could use the Html.Raw method:

    case "New": 
        Html.Raw("<tr class='info'>")
        break;

Also see MVC3 Razor: Displaying html within code blocks for other options such as:

    case "New": 
       @:<tr class='info'>
       break;
like image 20
Justin Bicknell Avatar answered Oct 21 '22 00:10

Justin Bicknell