Search code examples
switch-statementblazorblazor-webassembly

Use switch case in Blazor for attribute


I would like to set the css class in blazor using property enum. Programmatically, a switch case would make sense.

How do I write a switch case for a attribute in Blazor?

at cs file:

public enum PastPresentFuture
{
    PAST,
    PRESENT,
    FUTURE
}

public MyObject
{
    public PastPresentFuture PastPresentFuture { get; set; }
}

at css file:

    
.past{
    color: grey;
    font-weight: 100;
}

.present {
    color: black;
    font-weight: 700;
}

.future {
    color: black;
    font-weight: 100;
}

at razor - file I tried: (NOT WORKING!)

<div class="
     @switch(myObject.PastPresentFuture)
     {
        case PastPresentFuture.PAST: past break; 
        case PastPresentFuture.PRESENT: present break;
        case PastPresentFuture.FUTURE: future break;
     } 
     one-more-class">

also I tried using a span: (NOT WORKING!)

case PastPresentFuture.PAST: <span>past</span> break;

I get the error:

RZ9979 Code blocks delimited by '@{...}' like '@{ switch(currentSitzungsAndUvsDays[i].PastPresentFuture){case PastPresentFuture.PAST:break; case PastPresentFuture.PRESENT:break;case PastPresentFuture.FUTURE:break;} }' for attributes are no longer supported These features have been changed to use attribute syntax. Use 'attr="@(x => {... }"'.

I can't find the right syntax for the switch case inside a Blazor class attribute. You know how to do?

My current workaround: (works)

<div class="
  @(myObject[i].PastPresentFuture == PastPresentFuture.PAST ? "past" : 
    myObject[i].PastPresentFuture == PastPresentFuture.PRESENT ? "present" : "future") 
      day">

Solution

  • Create a method that returns the css class:

    <div class="@GetCssClass(currentSitzungsAndUvsDays[i])">
        ...
    </div>
    
    string GetCssClass(MyObject myObject)
    {
       return myObject.PastPresentFuture switch
       {
           PastPresentFuture.PAST => "past",
           PastPresentFuture.PRESENT => "present",
           PastPresentFuture.FUTURE => "future"
       };
    }