Conditional Compilation is turned off in Razor?

Timmi4sa – I agree, there isn’t much of an answer as to why we are getting this error. I finally got a step closer to understanding it all so I thought i would share.

Conditional Compilation is defined my MS as this:

Conditional compilation enables JScript to use new language features
without sacrificing compatibility with older versions that do not
support the features. Some typical uses for conditional compilation
include using new features in JScript, embedding debugging support
into a script, and tracing code execution.

From what I can tell, we are really talking about a feature of VS. My current guess is this: VS lets you debug JS, but it has to know what the JS is in order to debug it. By default Conditional Compilation is off – I am guessing that there is some additional overhead involved. What we are doing when we are using @Model… in JS is doing exactly what the warning states (more or less) – creating conditional JS. The JS ends up being different things depending on the value of our C#/VB variables.

According to MS the solution is to turn Conditional Compilation on as mentioned above via the statement:

/*@cc_on @*/

While I tend to be a bit anal and prefer to avoid warnings, this may be one I just simply ignore (unless someone can educate me further as to why this is a bad idea).

If you really want the error to go away and do not like the Conditional Compilation flag, you can wrap the C#/VB code call in double quotes like below. But this feels dirty and only works because JS is loosely typed… (well with numeric types anyway, strings shouldn’t have a problem… regardless, this feels hacky)

"@Model.Items.Count()"

Edit: I went and did a little more research… I like the idea of CC even less after skimming this article: http://www.javascriptkit.com/javatutors/conditionalcompile.shtml. I think I will just be ignoring this warning.

I hope that helps explain away some of the mystery.

EDIT :

Another option is to throw a HiddenFor down on the form, give it an Id and then populate a JS variable from that field (jQuery makes this pretty easy). This is what I ended up doing for the time being. It eliminates warnings and I often want to compare the JS variable back to the original VMC field anyway. For those of you who need it:

@* Somewhere in your form - assuming a strongly typed view *@
@Html.HiddenFor(x => x.YourField, new { id = "SomethingMeaningful" })

// and then in your JS
$(document).ready(function(){
  ...
  var jsYourField = $("#SomethingMeaningful").val();
  ...
});

Please note that JS variable and MVC variables do not always ‘line up’ exactly right so you may need to do some casting or additional work when you copy the variable value into your JS.

Leave a Comment