我是一个使用 Razor 的菜鸟,现在我正在尝试从 JavaScript 函数中更新 Razor 变量。例如:
@{
bool myVariable = false;
}
<script type="text/javascript">
function Foo() {
if (some_condition)
{
@myVariable = true;
}
}
</script>
@if (myVariable)
{
<div>
<!-- stuff -->
</div>
}
这可能吗?如果可以,我该怎么做?
最佳答案
@myVariable
是一个服务器端变量,它在渲染页面之前从服务器获取其值
@myVariable
将打印变量的值,而不是分配给它,
因此 @myVariable = true;
的输出将是
false = true;
<小时/>
使用ajax从服务器获取内容
@{
bool myVariable = false;
}
<script type="text/javascript">
function Foo() {
if (some_condition)
{
$('#newContent').load('/News/GetLatest/10'); // call ajax to get content
}
}
</script>
<div id="newContent">
<!-- stuff -->
</div>
<小时/>
或者只有在客户端条件成立时才能显示 div
@{
bool myVariable = false;
}
<script type="text/javascript">
var showContent = @myVariable; // false
function Foo() {
if (some_condition)
{
showContent = true;
$('#newContent').show(); // show it
}
}
</script>
<div id="newContent" style="display: none;"> <!-- hidden by default -->
<!-- stuff -->
</div>
关于javascript - 从 JavaScript 函数中更新 Razor 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60048571/