简体   繁体   中英

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. 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. ViewBag was populated with respective keys\\value pairs in the action method that returns the view.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM