proper razor syntax for switch statement inside foreach
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;
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=
).