c# - 无法减少剃刀 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...
}
});
解决方案
该变量 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--;
推荐阅读
- scala - Akka Stream 的 Keep right/left/两者如何导致不同的输出?
- vue.js - laravel 5.8 中的 Vue,从 axios 响应动态填充表
- css - 在 ReactJS 中使用 Animate.css 和 react-animated-css
- android - DialogFlow Android SDK 需要 grpc-okhttp,但添加它会导致 Socket IO CLient 崩溃
- python - 显示来自模型 Django 的唯一值的表单
- excel - 运行时错误“91”:代码运行后未设置对象变量或块变量
- android - 接收 Recyclerview 数据时的 ProgressBar
- wpf - 相当于 Visual Studio 添加新页面 (WPF) 的命令行
- azure-active-directory - 可以使用数据工厂提取所有 Azure Active Directory 用户吗?
- authentication - 创建工业应用程序(本机/Web)的注意事项