2

I'm looking for the equivalent of an

#if DEBUG
   //view elements to show just for debug builds
#if

for views in MVC3/Razor. What's the idiomatic method for implementing this type of a setup?

blueberryfields
  • 40,523
  • 27
  • 86
  • 165

3 Answers3

3

You can use HttpContext.Current.IsDebuggingEnabled, it checks debug value in the web.config file.

For instance:

@if(HttpContext.Current.IsDebuggingEnabled) {
    //view elements to show just for debug builds
}

The other option is use write your own HttpHelper extension

public static class HtmlHelperExtensions
{
    public static bool IsDebug(this HtmlHelper helper)
    {
        #if DEBUG
          return true;
        #else
          return false;
        #endif
    } 
}

Then in your Razor code you can use it as:

@if (Html.IsDebug())
{ 
    //view elements to show just for debug builds
}
Vlad Bezden
  • 72,691
  • 22
  • 233
  • 168
3

That's too messy IMO. Views should be dumb, and focused on rendering HTML, not making build-based decisions.

Set properties in your view model if debug is configured, and render them out in the View.

If the properties are null (e.g non-debug), nothing will get rendered.

RPM1984
  • 70,934
  • 57
  • 219
  • 339
  • 2
    I'll just add that razor **can** handle preprocessor directives, but in this case it won't help because razor views are always compiled in debug mode, no matter what is set in web.config. – Lukáš Novotný Dec 07 '11 at 00:48
0

Don't think you can do that in Razor as it doesn't compile the same way as C# code does.

So I'd say the best way to do it would be to do it in your controller and add it to a value in your model.

Edit: Here's some more info. The person here is suggesting an extension method that loads the appropriate code whether it's in debug or not: asp.mvc view enteres #IF DEBUG in release configuration Since you haven't told us what you'd like to do, i can't give you any 'code' answers.

Community
  • 1
  • 1
mnsr
  • 12,097
  • 3
  • 51
  • 78