blueberryfields
blueberryfields

Reputation: 50388

Pre-processing equivalent for views in RAZOR/MVC 3

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?

Upvotes: 2

Views: 1907

Answers (4)

KyleMit
KyleMit

Reputation: 29987

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

Upvotes: 0

Vlad Bezden
Vlad Bezden

Reputation: 89637

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
}

Upvotes: 3

RPM1984
RPM1984

Reputation: 73132

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.

Upvotes: 3

mnsr
mnsr

Reputation: 12437

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.

Upvotes: 0

Related Questions