7

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.

1

2 Answers 2

18

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.

11

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>  
}
1
  • 1
    If Model.SomePop type is Boolean don't compare the value to true, just use the property as the if statement. if(Model.SomeProp) {
    – Muffun
    Commented Mar 23, 2018 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.