如何基于c#值在.cshtml文件中呈现js代码



你好,我又有一个问题。是否有可能在razor页面上渲染基于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>

上述基本情况

@可以帮助您获得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>

最新更新