Increment C# int inside tag

I have a .cshtml view where I click a .CompChoice element, it disapears and another one shows from a specific list.

However, it works for the first time i click the function when the count is at 0 and it counts up to 1, changing to the next value in the list. The second time i click the function the value of count is still 0, counting up one and displaying the same value. I want to keep the indexing in C# and the @{count++;} appears to works inside the script.

Why is the @{count++;} not persistent outside of the script tag?

@ {
int count = 0;
}

<script>
            $(".CompChoice").on('click', function () {
                $('#@shuffledList[count]').fadeOut('fast', function () {
                    @{ count++;}
            $('#@shuffledList[count]').show();
              });
        });
</script>

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As @VDWWD stated, the page is done rendering by the time you click the element. You see the count increase because as the page is being rendered it executes the count++ statement (it does not matter if you click anything on the page). Keep a javascript variable for the count and it will work as expected, however you will still need to pass this value back to your backend in order to do anything with it on the c# side.

Method 2

You should do that in plain javascript, starting from the server side value.

<script>
            var count = @{ count++;};
            $(".CompChoice").on('click', function () {
                $('#@shuffledList[count]').fadeOut('fast', function () {
                    count++;
            $('#@shuffledList[count]').show();
              });
        });
</script>

When the rendering ends, the user will get on the browser side

<script>
            var count = 1;
            $(".CompChoice").on('click', function () {
                $('#@shuffledList[count]').fadeOut('fast', function () {
                    count++;
            $('#@shuffledList[count]').show();
              });
        });
</script>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x