neizan neizan - 1 year ago 74
C# Question

ASP.NET MVC 3 Restrict access to a view based on time of year/accessible date range

I'm using ASP.NET MVC 3, with Razor views. I have two action methods (Get and Post) in a controller that have a single corresponding view (.cshtml file). In my app, I want to allow access to that view only during certain times of the year, let's call it the "accessible date range." During all times not within the accessible date range, I'd like the app to provide the user an error message instead of displaying the page. What is a good way to go about this? Could a custom attribute be used on the controller methods? Should the logic go directly in the two controller methods? Should I just use an

statement in the view file along with the appropriate logic? I'm not crazy about putting this logic in a view file, and would like suggestions for a cleaner option.

Answer Source

The simplest answer would be put the logic inside your controller:

public ActionResult SummerOnly()
   if (!(DateTime.Now > new DateTime(2012,8,8)))
       return View("Error");    

   return View("GoodView");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download