Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvc3 - Best practice to deal with data which are required for (almost) all requests?

I am creating an application in mvc3 and wondering how to deal with database data which is required for all application requests, some of them depends on a session, some of them depends on url pattern basically all data is in database.

Like to know best practice

like image 759
Prashant Lakhlani Avatar asked Dec 04 '25 21:12

Prashant Lakhlani


1 Answers

What I do in my applications and consider to be the best practice is to load your common data to the ViewBag on the Controller constructor.

For every project, I have a DefaultController abstract class that extends Controller. So, every controller in the project must inherit from DefaultController, instead of Controller. In that class' constructor, I load all data common to the whole project, like so:

// DefaultController.cs
public abstract class DefaultController : Controller
{
    protected IRepository Repo { get; private set; }

    protected DefaultController(IRepository repo)
    {
        Repo = repo;
        ViewBag.CurrentUser = GetLoggedInUser();
    }

    protected User GetLoggedInUser()
    {
        // your logic for retrieving the data here
    }
}


// HomeController.cs
public class HomeController : DefaultController
{
    public HomeController(IRepository repo) : base(repo)
    {
    }

    // ... your action methods
}

That way you will always have the logged in user available in your views.

like image 147
rdumont Avatar answered Dec 06 '25 11:12

rdumont