admin管理员组文章数量:1287627
In an index.cshtml I have the following working code similar to:
<script type="text/javascript">
if ('@Model.SomeCondition' === 'True'){
Do Something();
}
</script>
The === 'True'
seems like an odd hack to me to force Razor and JavaScript to get along. How can I refactor to use === true
? This doesn't give the same result. Can this be done with Razor and JavaScript?
In an index.cshtml I have the following working code similar to:
<script type="text/javascript">
if ('@Model.SomeCondition' === 'True'){
Do Something();
}
</script>
The === 'True'
seems like an odd hack to me to force Razor and JavaScript to get along. How can I refactor to use === true
? This doesn't give the same result. Can this be done with Razor and JavaScript?
-
6
Mixing Razor and Javascript is a bad idea. You should separate data from code using
data-*
attributes. – SLaks Commented Jun 2, 2015 at 15:33
3 Answers
Reset to default 9If the property isbool
, you can check in razor if condition following way:
<script type="text/javascript">
@if (Model.SomeCondition){
@:Do Something();
}
</script>
or:
<script type="text/javascript">
@if (Model.SomeCondition){
<text>
Do Something();
</text>
}
</script>
Assuming SomeCondition
is a string, remove the quotes, and make it conform to the lowercase form of javascript's booleans
<script language="javascript">
// just to be clear this is javascript, not server code
if (@Model.SomeCondition.ToLowerInvariant()){
.. //
}
</script>
If, however SomeCondition
is a boolean in server code, you need to first convert to a string and make it lowercase
<script language="javascript">
// just to be clear this is javascript, not server code
if (@Model.SomeCondition.ToString().ToLowerInvariant()){
.. //
}
</script>
Just write the if satement in c#/razor with the javascript you want to execute in there.
Example:
@if(boolVariable)
{
<script>
//javascript here
</script>
}
本文标签: cUsing Razor Syntax within JavaScript Conditional StatmentStack Overflow
版权声明:本文标题:c# - Using Razor Syntax within JavaScript Conditional Statment - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741315530a2371890.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论