How do I render js code in .cshtml file based on C# value

238 views Asked by At

Hi gus I have a question again. Is it posible to render js code baised on C# value in razor page ? And how do I do that ? For example:

@{
    double numberA = (double)ViewData["someVal"];
}
<h1>SOME HTML</h1>
<script>

let myVal = "Number is small";
@if (numberA > 5) {            // C# code checking c# variable that comes via ViewModel fom server
    myVal = "Number is large"  // change js variable
}
console.log(myVal); // prints phrase to browser console based on what was received from backend
</script>

basicaly sittuation described above

1

There are 1 answers

1
Yiyi You On BEST ANSWER

@can help you get the value of C# variable.You can try to use the following code:

@{
    double numberA = (double)ViewData["someVal"];
}
<h1>SOME HTML</h1>
<script>
    let myVal = "Number is small";
    if (@numberA > 5) {
        myVal = "Number is large";
    }
    console.log(myVal);
</script>