-1

I'm working on an ASP.NET MVC app using .NET Framework 4.6.1 in Visual Studio 2015 Update 3. I'm planning to use the Faker.Data library (https://github.com/FermJacob/Faker.Data) to produce fake data for debug mode in development; it might be some time before I have real data which will reside in SQL Server.

I need to have the views use this fake data in debug mode. Is it possible to use something like this in the cshtml view file to switch the data?

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

The view currently has this statement at the top to provide a strongly-typed model:

@model MyProject.DAL.Customer

Thanks.

Alex
  • 34,699
  • 13
  • 75
  • 158
  • 1
    Your choice of datasource should go in the controller and be sent to the view. The view shouldn't have any code in it to select the datasource. – Ilnetd Oct 21 '16 at 20:52
  • Thanks, @Ilnetd. Dang, was afraid you'd say that. Was hoping I could avoid that, but in MVC, what you described is the correct way of doing it. – Alex Oct 21 '16 at 20:54

3 Answers3

3

Preprocessor usualy doesn't work in razor correctly, you can put that code like this

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

But this code doesn't return expected result. you can define an extention method for HtmlHelper class like this:

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

At the end you can call that extention method in razor syntax like this one:

@if(Html.IsDebugMode()){}
Mehdi
  • 1,731
  • 1
  • 18
  • 33
2

HttpContext.Current.IsDebuggingEnabled is available in your views. However, your view should be receiving a View Model from the controller, as opposed to the data/datasource being selected in the View

willwolfram18
  • 1,747
  • 13
  • 25
1

I recommend to use [Conditional("DEBUG")] instead of #if DEBUG as it may cause to encounter some kind of compile errors. For more information have a look at If you're using “#IF DEBUG”, you're doing it wrong. Hope this helps...

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63