I've got this multi-line javascript snippet:
$.getJSON('@Url.Action("ReconBases")',
{ modelId: selectedModelId },
function(selectItems) {
buildDropDown('#SelectedReconId', selectItems);
});
I want to conditionally add this script to the page based on a view model variable, like this:
@if ( Model.GetBases )
{
<snippet above>
}
Can anyone tell me if this is possible and the right syntax for doing this? I've tried using @: and Html.Raw, but I can't seem to get the right format for it to work.
Output code inside a conditional in Razor must be surrounded by HTML tags such as <div></div>
(this "flags" it as output, and not more C# code).
If no particular tag suits your needs you can use the special <text></text>
that are Razor specific. These are NOT outputted during rendering.
@if ( Model.GetBases )
{
<text>
<snippet above>
</text>
}
This also applies to for
, foreach
, etc.
You can also make conditon of c# with javascript some code snippet here.
Multi-line JavaScript Code
Use <text></text>
@if ( Model.SomeProp == true)
{
<text>
<Your javaScript Multi-line code>
</text>
}
Single-line JavaScript code
Use @:
@if ( Model.SomeProp == true)
{
@:<Your javaScript single code>
}
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