C# and ASP.NET MVC: Using #if directive in a view

前端 未结 7 2113
不知归路
不知归路 2020-12-03 04:05

I\'ve got a conditional compilation symbol I\'m using called \"RELEASE\", that I indicated in my project\'s properties in Visual Studio. I want some particular CSS to be app

相关标签:
7条回答
  • 2020-12-03 04:44

    Below is the Razor syntax for conditional compiler directives. It loads the developer version of jquery when DEBUG variable is set in VS profile or web.config. Otherwise the min version is loaded.

        @{
    #if (DEBUG)
        }
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.js"></script>
        @{    
    #else
        }
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
           <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
        @{
    #endif
        }
    
    0 讨论(0)
  • 2020-12-03 04:47

    A better, more generic solution is to use an extension method, so all views have access to it:

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

    You can then use it like follows in any view (razor syntax):

    @if(Html.IsReleaseBuild())
    ...
    
    0 讨论(0)
  • 2020-12-03 04:49

    You can use ViewBag instead of viewmodel (but viewmodel-like approach is better) :

    Controller :

    controller code

    View :

    @{
       bool hideYoutubeVideos = ViewBag.hideYoutubeVideos ?? false;     
    }
    

    Usage :

    @if (!hideYoutubeVideos)
    {
         <span>hello youtube</span>
    }
    

    Also, be sure, that NIKITA_DEBUG variable exist in build tab of your project :

    build tab

    0 讨论(0)
  • 2020-12-03 04:50
    @if (HttpContext.Current.IsDebuggingEnabled)
    {
        // Debug mode enabled. Your code here. Texts enclosed with <text> tag
    }
    
    0 讨论(0)
  • 2020-12-03 04:52

    For me, the code below has worked very well. When the application is Debugging my buttons appear, when is Release, don't.

    @if (this.Context.IsDebuggingEnabled)
    {
        <button type="button" class="btn btn-warning">Fill file</button>
        <button type="button" class="btn btn-info">Export file</button>
    } 
    
    0 讨论(0)
  • 2020-12-03 04:59

    In your model:

    bool isRelease = false;
    
    <% #if (RELEASE) %>
        isRelease = true;
    <% #endif %>
    

    In your view:

    <% if (Model.isRelease) { %>
        <div class="releaseBanner">Banner text here</div>
    <% } else { %>
        <div class="debugBanner">Banner text here</div>
    <% } %>
    
    0 讨论(0)
提交回复
热议问题