I'm trying to include some JS in a view within a Razor conditional, but it keeps trying to interpret my JS as VB:
@If includeMoreJs Then
@<script type="text/javascript" src="/some-js-file.js"></script>
<script type="text/javascript" src="/some-other-js-file.js"></script>
<script type="text/javascript">
function someFunction(p) {
if (p) foo();
else bar();
}
</script>
End If
I've also tried this with the <text> psuedo element as described here: Using Razor within JavaScript
@If includeMoreJs Then
<text>
<script type="text/javascript" src="/some-js-file.js"></script>
<script type="text/javascript" src="/some-other-js-file.js"></script>
<script type="text/javascript">
function someFunction(p) {
if (p) foo();
else bar();
}
</script>
</text>
End If
but still no luck... How can I get VB to leave my JS alone?
OK having forced myself to create my first ever .vbhtml file, and googling around, you were very nearly there with the <text> block.
This page is a pretty good resource for VB Razor syntax.
There are two ways around this, depending how much html you have in your @If:
Option 1: @:
This is needed on every line so generally you would only use it if there is only one line in your If:
@If includeMoreJs Then
@:<script type="text/javascript" src="/some-js-file.js"></script>
@:<script type="text/javascript" src="/some-other-js-file.js"></script>
@:<script type="text/javascript">
@: function someFunction(p) {
@: if (p) foo();
@: else bar();
@:
@:</script>
End If
.. Very pretty
Option 2: @<text>
Because VB can have XML as stated in this answer, a plain <text> will be interpreted as VB code, not razor. So in VB, compared to C#, you need to use @<text> to have a block of HTML:
@If includeMoreJs Then
@<text>
<script type="text/javascript" src="/some-js-file.js"></script>
<script type="text/javascript" src="/some-other-js-file.js"></script>
<script type="text/javascript">
function someFunction(p) {
if (p) foo();
else bar();
}
</script>
</text>
End If
This parses fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With