【问题标题】:Change data for an ASP.NET MVC view based on debug/release mode根据调试/发布模式更改 ASP.NET MVC 视图的数据
【发布时间】:2017-03-04 06:28:53
【问题描述】:

我正在使用 Visual Studio 2015 Update 3 中的 .NET Framework 4.6.1 开发 ASP.NET MVC 应用程序。我计划使用 Faker.Data 库 (https://github.com/FermJacob/Faker.Data) 生成用于调试的假数据发展模式;可能需要一段时间才能获得将驻留在 SQL Server 中的真实数据。

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

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

视图当前在顶部有这个语句来提供一个强类型模型:

@model MyProject.DAL.Customer

谢谢。

【问题讨论】:

  • 您选择的数据源应该进入控制器并发送到视图。视图中不应有任何代码来选择数据源。
  • 谢谢,@Ilnetd。 Dang,怕你这么说。希望我可以避免这种情况,但在 MVC 中,您所描述的是正确的做法。

标签: c# asp.net asp.net-mvc faker


【解决方案1】:

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

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

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

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

最后,您可以像这样以 razor 语法调用该扩展方法:

@if(Html.IsDebugMode()){}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-07
        • 1970-01-01
        • 2013-06-22
        相关资源
        最近更新 更多