【问题标题】:Update Razor variable from within a javascript function从 javascript 函数中更新 Razor 变量
【发布时间】:2020-05-19 18:15:20
【问题描述】:

我是使用 Razor 的菜鸟,现在我正在尝试从 javascript 函数中更新 Razor 变量。例如:

@{
    bool myVariable = false;
}

<script type="text/javascript">

    function Foo() {
       if (some_condition)
       {
          @myVariable = true;
       }
    }

</script>

@if (myVariable)
{
   <div>
      <!-- stuff -->
   </div>
}

这可能吗?如果是这样,我该怎么做?

【问题讨论】:

标签: javascript asp.net-mvc razor


【解决方案1】:

@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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2013-09-24
    相关资源
    最近更新 更多