Conditional compilation does not work
Asked Answered
P

1

5

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

Parental answered 17/8, 2011 at 14:36 Comment(1)
#4696675 How about this?Pica
S
7

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.

Sugared answered 17/8, 2011 at 15:11 Comment(2)
The problem is that this code should be executed for all pages. What is a CSS file for all pages. Once a controller has only one may ask, would have to put in all the controllers and that I did not want. The code is in _Layout.cshtml (master layout) Why can not I use the Direct View?Parental
see my additional info in my answer - perhaps it will work for you too.Sugared

© 2022 - 2024 — McMap. All rights reserved.