基于 debug/release 模式更改 ASP.NET MVC 视图的数据

Change data for an ASP.NET MVC view based on debug/release mode

我正在 Visual Studio 2015 Update 3 中使用 .NET Framework 4.6.1 开发 ASP.NET MVC 应用程序。我打算使用 Faker.Data 库(https://github.com/FermJacob/Faker.Data) 为开发中的调试模式生成虚假数据;我可能需要一段时间才能拥有将驻留在 SQL 服务器中的真实数据。

我需要让视图在调试模式下使用这个假数据。是否可以在cshtml视图文件中使用类似的东西来切换数据?

#if DEBUG
    // Point to fake data for this view
#else
    // Point to release data for this view
#endif

视图当前在顶部有此语句以提供强类型模型:

@model MyProject.DAL.Customer

谢谢。

预处理器通常不能在 razor 中正常工作,你可以像这样输入代码

@{
#if DEBUG
    // Point to fake data for this view
#else
    // Point to release data for this view
#endif
}

但是这段代码没有 return 预期的结果。 您可以像这样为 HtmlHelper class 定义扩展方法:

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

最后你可以像这样用剃刀语法调用扩展方法:

@if(Html.IsDebugMode()){}

HttpContext.Current.IsDebuggingEnabled 在您的视图中可用。但是,您的视图应该从控制器接收视图模型,而不是在视图

中选择 data/datasource

我建议使用 [Conditional("DEBUG")] 而不是 #if DEBUG 因为它可能会导致遇到某种编译错误。有关详细信息,请查看 If you're using “#IF DEBUG”, you're doing it wrong。希望这有助于...