Conditional Compilation Symbol on cshtml and aspx

According to msdn, you can define symbols/constants for the c# compiler and use them in your code as compile conditions using the #if directive.

Those symbols can be used to specify conditions for compilation. However, CSHTML (MVC Razor), ASPX (WebForms) and other ASP.NET pages do not recognize project level compilation symbols.

These directives are compile time only. ASP.NET pages are compiled at runtime on the server. You can tell in Visual Studio when the directive will affect code, it will be greyed out:

directive_example

To make ASP.NET use the directive when your page is being compiled at runtime, you need to set them in the web.config file. Here is an example:

web.config:

<configuration>
  <system.codedom>
    <compilers>
      <compiler
        language="c#;cs;csharp" extension=".cs"
        compilerOptions="/d:CUSTOMSYMBOL"
        type="Microsoft.CSharp.CSharpCodeProvider, 
        System, Version=4.0.0.0, Culture=neutral, 
        PublicKeyToken=b77a5c561934e089" />
    </compilers>
  </system.codedom>

cshtml file:

@{
#if CUSTOMSYMBOL
}
    [your code here]
@{
#endif                   
}

PS: If the links are broken, please comment, Thank you!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s