在JavaScript条件语句中使用Razor语法
Using Razor Syntax within JavaScript Conditional Statment
在索引。我有以下类似的工作代码:
<script type="text/javascript">
if ('@Model.SomeCondition' === 'True'){
Do Something();
}
</script>
=== 'True'
对我来说似乎是一个奇怪的hack,迫使Razor和JavaScript相处。我如何重构以使用=== true
?这不会得到相同的结果。这可以用Razor和JavaScript完成吗?
如果属性为bool
,则可以按以下方式检查剃刀是否符合条件:
<script type="text/javascript">
@if (Model.SomeCondition){
@:Do Something();
}
</script>
或:
<script type="text/javascript">
@if (Model.SomeCondition){
<text>
Do Something();
</text>
}
</script>
假设SomeCondition
是一个字符串,去掉引号,并使其符合javascript的布尔值的小写形式
<script language="javascript">
// just to be clear this is javascript, not server code
if (@Model.SomeCondition.ToLowerInvariant()){
.. //
}
</script>
但是,如果SomeCondition
在服务器代码中是布尔值,则需要首先转换为字符串并使其小写
<script language="javascript">
// just to be clear this is javascript, not server code
if (@Model.SomeCondition.ToString().ToLowerInvariant()){
.. //
}
</script>
只需在c#/razor中编写if语句,并在其中执行您想要执行的javascript。
的例子:
@if(boolVariable)
{
<script>
//javascript here
</script>
}
相关文章:
- 铬:“;未捕获的语法错误:意外的标记:"
- 在挖空.js模板中保留 Razor 语法突出显示
- 在具有 Razor 语法的表元素中使用折叠项
- 如何使用 razor 语法设置 javascript 变量或调用函数
- 如何正确地将javascript与razor语法结合起来
- Javascript 中的 C# Razor foreach 循环语法
- 动态2d数组,语法错误JavaScript和Razor
- 使用Razor语法调用JavaScript函数
- 混合JavaScript和Razor语法
- 在视图中混合使用razor语法和Javascript
- ASP.NET MVC4,Javascript中的Razor:页面运行,但VS2012中出现语法错误
- 使用Razor c#语法命名id
- 在执行razor语法后执行脚本
- Razor语法防止在Razor代码段后面有空格
- 在Asp.net MVC Razor语法中使用JavaScript变量
- 外部Javascript中的Razor语法
- asp.net mvc -如何在Razor语法中使用JavaScript
- 在JavaScript条件语句中使用Razor语法
- 如何用razor语法填充本地URL
- 我的“数据”在哪里?Razor语法中的Ajax选项