Tuesday, April 21, 2020

#if DEBUG Preprocessor Directive on ASP.NET Web Forms Markup

I have a JavaScript that I want to include only on Release mode of my ASP.NET Web Forms app. The script will reside in the markup. To do that I will need to use #if DEBUG. But to have it working in the markup takes me a while to figure out.

Problem

First, I tried wrapping my script with the following code on the markup under <head> tag and it doesn't work.

<% #if !DEBUG %>
<script>
alert('Hello World!');
</script>
<% #endif %>

Next, after reading some articles online, I tried to wrap my code using the following code and it still doesn't work.

<% if (!Debugger.IsAttached) { %>
    <script>
        alert('Hello World!');
    </script>
<% } %>

Solution

Finally, the one that works for me is when I wrap the whole thing with <asp:PlaceHolder> tag:

<asp:PlaceHolder runat="server"> 
<% #if !DEBUG %>
    <script>
    alert('Hello World!');
    </script>
    <% #endif %>
</asp:PlaceHolder>

No comments:

Post a Comment