JavaScript if statement aren't working with Model props

2033

Member
Joined
May 11, 2025
Messages
16
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.
 

@Skydiver, @Justin

I don't know if I should ask a new question or continue here.

How can I pass an ID of an entity to a controller method if I'm on the client side? I mean, I cannot pass @Model.ID. Right now I'm passing @Model[0].Id, but I need it to be dynamic.

JavaScript:
$("#BtnFav").on("click", function () {
        $.ajax({
        type: "POST",
        url:  '@Url.Action("Favorite", "Home")',
        data: { id: @Model[0].Id },
        success: function (res) {
            if (res.isFavorite) {
                $(this).css("background-color", "yellow");
            }
            else {
                $(this).css("background-color", "transparent");
            }
        }
    })
});

The model of a view is a list of entities. I'm using Ajax to switch between them. Where can I store that ID so that if I press a button, I can send an ID of the current entity?
 
In your JavaScript, pull the value from the DOM element, not from the model. Recall that you put your id in your hidden field in the DOM if you following any standard tutorial regarding how to use MVC or Razor.
 
In your JavaScript, pull the value from the DOM element, not from the model. Recall that you put your id in your hidden field in the DOM if you following any standard tutorial regarding how to use MVC or Razor.

Still don't understand. The model of a view is a List<WordViewModel>. How can I have a hidden input for this collection? I switch between this collection using Ajax.

On a click of buttons loadWord method is called.

On line 46 I need somehow to pass an ID of a cuttent entity.:
<script type="text/javascript">
    var currentIndex = 0;
    var totalCount = @Model.Count;

    function loadWord(index) {
        $.ajax({
            url: '@Url.Action("SwitchWord", "Home")',
            type: 'GET',
            data: { index: index },
            success: function (data) {
                $("#BtnFav").css("background-color", data.isFavorite ? "yellow" : "transparent");

                $("#counter").text((index + 1) + "/" + totalCount);
                $("#wordName").text(data.name);
                $("#wordDefinition").text(data.definition);
                $("#wordImage").attr("src", data.imagePath);

                // Enable/Disable buttons based on index
                $("#BtnPrev").prop("disabled", index === 0);
                $("#BtnNext").prop("disabled", index === totalCount - 1);

                currentIndex = index;
            },
            error: function () {
                alert("No more items.");
            }
        });
    }

    $("#BtnNext").on("click", function () {
        if (currentIndex < totalCount - 1) {
            loadWord(currentIndex + 1);
        }
    });

    $("#BtnPrev").on("click", function () {
        if (currentIndex > 0) {
            loadWord(currentIndex - 1);
        }
    });

    $("#BtnFav").on("click", function () {
            $.ajax({
            type: "POST",
            url:  '@Url.Action("Favorite", "Home")',
            data: { id: @Model[0].Id },
            success: function (res) {
                if (res.isFavorite) {
                    $(this).css("background-color", "yellow");
                }
                else {
                    $(this).css("background-color", "transparent");
                }
            }
        })
    });
</script>

This method from a controller returns a single word to display.:
[HttpGet]
public IActionResult SwitchWord(int index = 0)
{
    if (index < 0 || index >= _set.Words.Count)
    {
        return NotFound();
    }
    return Json(_set.Words[index]);
}

Should I somehow modify my model for the view so that I have an ID for each word or something else?
 
It's not a matter of changing your model. It's a matter of changing our view.

Which tutorial or book are you following to learn how to use MVC or Razor? Most of them will show how to get a table or grid view that lists all the rows (or a paged view of all rows) of a table. They will often either have an explicitly visible Id column or a hidden Id field stashed away on one of the rows.

For example the following tutorial has:
C#:
@Html.ActionLink("Edit", "Edit", new { id=item.ID })
which will create link that passes the id as URL parameter to the Edit action of the controller.

 
Most of them will show how to get a table or grid view that lists all the rows (or a paged view of all rows) of a table.

Yes, I know about that, but the neat part about that specific view is that it doesn't display all of the items at once (e.g., in a table). I have that one, and yeah, it works. But here I'm displaying only one item at a time out of the whole collection. I'm using next/prev buttons in order to navigate through that collection.
 
Well, while I was writing my response, I pondered. Do I really need a collection of items? Since I'm using only one at a time, maybe I should dig in that direction.
 
Back
Top Bottom