[英]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.