Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Razor how to make complex javascript conditional?

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.

like image 465
pathrider Avatar asked Mar 11 '12 02:03

pathrider


2 Answers

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.

like image 183
Timeout Avatar answered Nov 10 '22 05:11

Timeout


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>  
}
like image 9
Rikin Patel Avatar answered Nov 10 '22 07:11

Rikin Patel