Search code examples
asp.net-corerazorasp.net-core-mvc

Conditional style inside an element


How do I do a conditional style based on a MODEL value. Such as below, I want the column either Green or Orange based on a value from the Model

<div class="col-6" 
     @Model.QuestionAnswers[i].answers[j].answerSelected == true 
           ? style="background-color:green" 
           : style="background-color:darkorange">

Solution

  • Like this:

    <div class="col-6" 
         style="@(Model.QuestionAnswers[i].answers[j].answerSelected == true ? "background-color: green;" : "background-color: darkorange;")">
    

    But its cleaner to create a variable for the calculated style:

    @{
        var calculatedStyle = Model.QuestionAnswers[i].answers[j].answerSelected == true ? "background-color: green;" : "background-color: darkorange;";
    }
    <div class="col-6" style="@calculatedStyle">