简体   繁体   English

如何使用Razor视图引擎在JavaScript中正确混合C#代码。 我希望根据ViewBag中的值包含或省略Javascript

[英]How do I properly mix C# code within JavaScript, using Razor view engine. I wish to include or omit Javascript based on a value in ViewBag

So I only want this JavaScript to be included in the response to the browser if ViewBag.L1Cat does not equal null. 因此,如果ViewBag.L1Cat不等于null,我只希望将此JavaScript包含在对浏览器的响应中。 At the moment I am getting the error: cannot perform run time binding on a null reference. 目前我收到错误: 无法对空引用执行运行时绑定。 And the debugger does not want to stop inside the if statement for some reason. 并且调试器由于某种原因不想在if语句中停止。 ViewBag was populated with respective keys\\value pairs in the action method that returns the view. ViewBag在action方法中填充了相应的键\\值对,返回视图。

 <script type="text/javascript">
 @{
    if(ViewBag.L1Cat != null)
    {
       <text>              
          var FirstLevel = 
                    $('#MenuContainer')
                       .find('.FirstLevel')
                       .attr('@(ViewBag.RootCat.ToString());');
       </text>        
     }
   }    
 </script>

Is it absolutely necessary to omit the code? 是否绝对有必要省略代码?

You might find it cleaner to take this approach: 您可能会发现采用这种方法更清洁:

<script type="text/javascript">
var doStuff = @(ViewBag.L1Cat != null ? "true" : "false");
if (doStuff)
{
var FirstLevel = $('#MenuContainer').find('.FirstLevel').attr('@(ViewBag.RootCat.ToString())');
}
</script>

Alternatively 另外

<script type="text/javascript">
@if(ViewBag.L1Cat != null)
{
 <text>              
  var FirstLevel = $('#MenuContainer').find('.FirstLevel').attr('@(ViewBag.RootCat.ToString())');
 </text>        
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Javascript中比较C#Viewbag中的值? - How can I compare a value from C# Viewbag in Javascript? 我如何使用javascript var作为键来混合剃刀语法和javascript语法以更改哈希表值 - How can i mix razor syntax and javascript syntax to change a hashtable value using a javascript var as key 我在C#中有一个for循环,可与Unity引擎配合使用。 但是我该怎么做,使其只调用一次循环? - I have a for loop in C#, which works in conjuction with Unity engine. But how do i make it so it only calls the loop once? 混合 Razor 和 Javascript 代码 - Mix Razor and Javascript code 如何使用 foreach 在 Razor 中设置 Viewbag 值? - How can i set Viewbag value in Razor by using foreach? 如何在Razor视图中正确发布一个十进制值? - How do I properly post a decimal value in a Razor View? 如何使用对象MVC 5 C#的Javascript列表填充剃须刀DropDownListFor - How do I fill razor DropDownListFor with Javascript list of object MVC 5 C# 如何连接嵌入在 Razor 页面 javascript 中的 C# 中的字符串? - How do I concatenate strings in C# embedded in Razor page javascript? 在razor代码下检查javascript中的viewbag null - Check viewbag null in javascript under razor code MVC需要在剃刀视图中混合字符串和C#代码 - MVC Need to mix string and c# code in the razor view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM