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
  • 45,910
  • 28
  • 89
  • 168

4 Answers4

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
  • 83,883
  • 25
  • 248
  • 179
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
  • 72,246
  • 58
  • 225
  • 350
  • 3
    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

Preprocessor directives (#if) are a language feature C#, which you can enter by using a razor code block (@{}) and then use a explicit delimited transition (<text></text>) or an explicit line transition (@:) to conditionally add html like this:

@{

#if DEBUG
{
    @:<div>Debug Mode</div>
}
#else
{
    <text>
        <div>
            Release Mode
        </div>
    </text>
}
#endif

}

See Also: Preprocessor directives in Razor

KyleMit
  • 30,350
  • 66
  • 462
  • 664
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,337
  • 4
  • 53
  • 79