Zidane
Zidane

Reputation: 1904

How and where to declare Global variable that is accessible throughout my entire MVC /single page application

I am using asp.net mvc with EF . for each login session in my app in the controllers I can get the user ID for whoever is logged in using var userID = int.Parse(User.Identity.Name); however I would also like to use this in other repository and service classes is the a way to initially obtain this value per session and store its value in a global variable that can be accessed by every class in solution

Upvotes: 1

Views: 1548

Answers (2)

Peter B
Peter B

Reputation: 24147

In MVC the User is known in the context of a Page request, but that is not the case in other (repository/service/BL/DAL) classes. They do not - and should not! - have any knowledge about MVC.

You could make life easier however by creating a base class for all your controllers, implement some methods & properties there, and let the actual controllers inherit from it. Like this:

MyBaseController.cs

public abstract class MyBaseController : Controller
{
    public int UserID
    {
        get { return int.Parse(User.Identity.Name); }
    }

    // other useful methods & properties...
}

MyController.cs

public class MyController : MyBaseController
{
    public ActionResult Index()
    {
        var data = MyService.GetData(UserID);
        return View(data);
    }
}

Upvotes: 0

Karthik M R
Karthik M R

Reputation: 990

Since the data you need to store is session level, Store the data in Session variable. eg. Session["UserId"] = userId. You can access the userid anywhere from your application for that session.eg. var userId = (int)Session["UserId"]

Upvotes: 1

Related Questions