【问题标题】:Conditional compilation does not work条件编译不起作用
【发布时间】:2011-10-29 00:11:48
【问题描述】:

在stackoverflow上阅读this post希望在为发布模式编译时加载不同的css。

代码:

@{ #if (Debug) 
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#else
<link href="@Url.Content("~/Content/Site-min.css")" rel="stylesheet" type="text/css" />
#endif 
}

尝试 2

@{ #if (Debug) }
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
@{ #else }
<link href="@Url.Content("~/Content/Site-min.css")" rel="stylesheet" type="text/css" />
@{ #endif  }

我尝试使用大写的 DEBUG 但是编译Debug到Release的时候没有任何改变是没有效果的

【问题讨论】:

标签: visual-studio-2010 asp.net-mvc-3 c#-4.0 razor conditional-compilation


【解决方案1】:

根据this SO post,如果你想让这种事情起作用,你可以在你的模型中使用一个属性来驱动视图的条件内容,所以C#通过设置模型的布尔值(IsDebug,或其他)编译时指令的东西和视图依赖于它。

所以你的模型会结束做这样的事情:

bool IsDebug = true;

#if (!DEBUG)
IsDebug = false;
#endif

你的视图会做这样的事情:

@if(Model.IsDebug) 
{ 
}
else
{
}

我想,您也可以使用 ViewBag/ViewData 来保存该布尔值。


更新:

根据您的 cmets,以下是您可以做的事情:

创建一个继承自Controller 的新BaseController 类。

public abstract class BaseController : Controller
{
   ...
   protected BaseController()
   {
      bool indebug = false;

      #if DEBUG
      indebug = true;
      #endif

      ViewBag.InDebug = indebug;
   }
}

并让您的 Controller 继承自 this 而不是 Controller。

然后在你的 _Layout.cshtml 中你可以这样做:

@if (ViewBag.InDebug)
{
}
else
{
}

这似乎工作正常。

【讨论】:

  • 问题是这段代码应该对所有页面执行。什么是所有页面的 CSS 文件。一旦一个控制器只有一个可能会问,将不得不把所有的控制器和我不想要的。代码在_Layout.cshtml (master layout) 为什么我不能使用Direct View?
  • 在我的回答中查看我的附加信息 - 也许它也对你有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多