JavaScript if statement aren't working with Model props

2033

Member
Joined
May 11, 2025
Messages
12
Programming Experience
1-3
Script. Alert 2 and 3 won't show bc of Model prop on line 4:
<script type="text/javascript">
    const BtnFav = document.getElementById('BtnFav');
    alert('1');
    if (@Model.CurrentWord.IsFavorite) {
        alert('2');
        BtnFav.style.backgroundColor = "yellow";
    }
    else {
        alert('3');
        BtnFav.style.backgroundColor = "transparent";
    }
</script>

Although everything is working in this one on line 4 and 12:
<script type="text/javascript">
    const BtnPrev = document.getElementById('BtnPrev');
    const BtnNext = document.getElementById('BtnNext');
    if (@Model.Index === 0) {
        BtnPrev.style.pointerEvents="none";
        BtnPrev.style.cursor="default";
    }
    else {
        BtnPrev.style.pointerEvents="auto";
        BtnPrev.style.cursor="pointer";
    }
    if (@Model.Index === @Model.Count - 1){
        BtnNext.style.pointerEvents="none";
        BtnNext.style.cursor="default";
    }
    else {
        BtnNext.style.pointerEvents="auto";
        BtnNext.style.cursor="pointer";
    }
</script>

Model of the view. On line 6 is the property which is located inside if statement:
public class CurrentWordViewModel
{
    public int Index { get; set; }
    public int Count { get; set; }
    public int SetId { get; set; }
    public WordViewModel CurrentWord { get; set; } = new();
}

And WordViewModel basically contains bool IsFavorite property. I truly do not understand why it's not working. Tried IsFavorite === true. Also tried to define a variable, then assign it, and then use it inside javascript.

Also I was thinking about direct descendent property thing. I rellocated a bool property into the Model, tried to make if statement like this: @Model.IsFavorite and still no result.
 
When you do a view code in the browser, what code is generated by Razor for that if statement?
 
изображение_2025-05-25_100432138.png
 
Looks to me that gives you your answer, albeit, I would have expected the alert('3') to fire.
 
If by chance this is ASP.NET Core, see the Dialog1 page in this GitHub repository project, which defines a Bootstrap 5x modal that assigns a modal value that can be accessed OnPost.

The key is that the code gets the checked value of a checkbox, not value property.
 
View attachment 3402
"True or False is not defined" it says in the error tab

Ah! That would explain why neither alerts were firing. The JavaScript couldn't even be parsed to be executed.

And that makes perfect sense because Razor simply returned the value of the expression after the @. It won't automatically convert the value into something that JavaScript can interpret.
 
Back
Top Bottom