【问题标题】:How do I render js code in .cshtml file based on C# value如何根据 C# 值在 .cshtml 文件中呈现 js 代码
【发布时间】:2022-12-18 15:28:59
【问题描述】:

嗨,我又有问题了。是否可以在剃须刀页面中基于 C# 值呈现 js 代码?我该怎么做?例如:

@{
    double numberA = (double)ViewData["someVal"];
}
<h1>SOME HTML</h1>
<script>

let myVal = "Number is small";
@if (numberA > 5) {            // C# code checking c# variable that comes via ViewModel fom server
    myVal = "Number is large"  // change js variable
}
console.log(myVal); // prints phrase to browser console based on what was received from backend
</script>

基本情况如上

【问题讨论】:

    标签: javascript asp.net-core model-view-controller razor viewdata


    【解决方案1】:

    @可以帮你获取C#变量的值。你可以尝试使用下面的代码:

    @{
        double numberA = (double)ViewData["someVal"];
    }
    <h1>SOME HTML</h1>
    <script>
        let myVal = "Number is small";
        if (@numberA > 5) {
            myVal = "Number is large";
        }
        console.log(myVal);
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2021-10-07
      • 2014-02-06
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多