How to change the color of a div via javascript with one condition

2

I'm trying to change the color of a div if the following condition is true, if( @ViewBag == "reservado" ) , but I can not, could someone tell me what the code would look like with that condition described above?

I'm programming in Asp.NET

As% w_that I want to change the color is this:

<div class="num">001</div>

Last code I tried:

function trocaCor(){
    var condi = @ViewBag.status;

    if( condi == "reservado"){
        document.getElementById("num").style.backgroundColor = green;
    }

}

But I do not know if this is correct, I want it to be executed when the page is loaded (if it is correct).

I also tried the following code:

if( @ViewBag == "reservado" ){
    $('.num').css('background-color','#000000');
}

But it did not work out

    
asked by anonymous 05.10.2018 / 18:34

1 answer

1

Victor, the problem with using Javascript is that if it is an external file .js will not work, because @ViewBag only works on .cshtml page (if it is VB, .vbhtml ).

A simple way would be to create a css class with the style you want:

.reservado {
   background-color: #000000
}

In cshtml, make the condition, and add the class to a variable if it is true, otherwise leave empty, not to add any class:

string classeReservado = (@ViewBag.status == "reservado") ? "reservado" : "";

Dai, goes from div and uses this variable to apply the class:

<div class="@classeReservado">

If you still want to use Javascript and the file is external, you need to create the variable inside the file .cshtml , which is processed by asp-net and can read the contents of ViewBag :

var condi = '@ViewBag.status';
    
05.10.2018 / 18:42