Search code examples
visual-studio-2010asp.net-mvc-3c#-4.0razorconditional-compilation

Conditional compilation does not work


Reading this post here on stackoverflow want to load a different css when compiling for release mode.

Code:

@{ #if (Debug) 
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#else
<link href="@Url.Content("~/Content/Site-min.css")" rel="stylesheet" type="text/css" />
#endif 
}

Attempt 2

@{ #if (Debug) }
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
@{ #else }
<link href="@Url.Content("~/Content/Site-min.css")" rel="stylesheet" type="text/css" />
@{ #endif  }

I tried to DEBUG in uppercase But no change has no effect when compiling Debug to Release


Solution

  • According to this SO post, if you want this sort of thing to work, you can use a property in your Model to drive the View's conditional stuff, so the C# sets the Model's boolean (IsDebug, or whatever) via the compile time directive stuff and the View relies on that.

    So your Model would end doing something like:

    bool IsDebug = true;
    
    #if (!DEBUG)
    IsDebug = false;
    #endif
    

    and your View would do something like:

    @if(Model.IsDebug) 
    { 
    }
    else
    {
    }
    

    You could also use ViewBag/ViewData to hold that boolean value too, I suppose.


    UPDATE:

    Base on your comments, here's something you could do:

    Create a new BaseController class which inherits from Controller.

    public abstract class BaseController : Controller
    {
       ...
       protected BaseController()
       {
          bool indebug = false;
    
          #if DEBUG
          indebug = true;
          #endif
    
          ViewBag.InDebug = indebug;
       }
    }
    

    and have your Controllers inherit from this rather than Controller.

    Then in your _Layout.cshtml you could do this:

    @if (ViewBag.InDebug)
    {
    }
    else
    {
    }
    

    This seems to work OK.