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.

Sign up to request clarification or add additional context in comments.

Comments

12

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 Comment

If Model.SomePop type is Boolean don't compare the value to true, just use the property as the if statement. if(Model.SomeProp) {

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.