Reputation: 9297
In one of my Controllers
Action Method I get the current week number and it's passed to the View
. I realize that I could need the week number in other Controllers
and Views
, but I don't want to copy/paste the same code at different places in my project.
I'm looking for a simple and smart solution where I can reuse the code from just one place like a static class or a global object or something similar. If it was within the same Controller
I could have done a method to call, but since I need it from other Controllers
, I need another solution and I'm not sure how to achieve this? Any suggestions?
Upvotes: 0
Views: 39
Reputation: 415
You can create a class that inherits from Controller.
I create a BaseController class like so:
public class BaseController : Controller
{
protected someDBContext db = new someDBContext();
protected User currentUser;
public static ILog ErrorLogger = LogManager.GetLogger("ErrorLogger");
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (Session["UserID"] != null)
{
currentUser = UserToStaff.GetCurrentUser(
(int)Session["userId"],
db
);
}
ViewBag.currentUser = currentUser;
addNoticesToViewBag();
}..
I add functions and properties for common tasks like creating the dbContext, creating the currentUser object, and setting up logging in here.
Don't let it grow arms and legs though.. the Initialize is going to fire with every request.
Upvotes: 1