首页 > 解决方案 > 无法减少剃刀 ASP.NET Core MVC 中的局部变量

问题描述

这是我的 .cshtml 文件,我正在声明并将值分配给变量 x。当我单击 id 为“b”的按钮时,我希望使用此变量,然后将其减一,但是当我调试此项目时,我看到变量 x 并没有减少。我有什么错误?

@model IEnumerable<WebApplicationMVC.Models.Test>

@{
    ViewData["Title"] = "Testing";
    int x = Model.Count() - 1;
}

<script>

<div id="partial">
    @await Html.PartialAsync("Question", Model.ToList()[0])
</div>

<input type="button" id="b" value="next" class="btn btn-default" />

$("#b").click(function () {

    if (@x == 0) {
        window.alert("Finished")
        window.location.href = '@Url.Action("Index", "Subject")'
    }

    window.alert("Value of x is -> " + @x);

    $.ajax({
        url: '@Url.Action("Question", "Test")',
        type: 'GET',
        data: { id: '@Model.ToList()[x].ID' },
        success: function (result) {
            $("#partial").html(result);
        }
    });

    @{ 
        x--;         //this doesn't work...
    }

});

标签: c#asp.net-mvcrazor

解决方案


该变量 x 在 C# 中,在服务器上运行。它永远不会到达浏览器。

当在浏览器中单击某些内容时,您希望变量减少。
改用 Javascript 变量:

<script>
    var x = @(Model.Count() - 1);  // javascript variable, initialised to a value from Razor

    if (x == 0)
    {
       // finished
    }

    window.alert("Value of x is -> " + x);

    x--;

推荐阅读