MVC3 - 最佳实践来处理所需要的(几乎)所有请求的数据? [英] Mvc3 - Best practice to deal with data which are required for (almost) all requests?
问题描述
我创建的MVC3应用程序,不知道如何处理这是需要所有应用程序请求数据库中的数据,他们中的一些依赖于一个会议上,一些人依靠URL模式基本上所有的数据在数据库中。
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.
想知道最好的做法
推荐答案
我在应用程序做些什么,并认为是最好的做法是,你常用的数据加载到ViewBag在控制器的构造函数。
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.
有关每一个项目,我有一个扩展控制器一DefaultController抽象类。因此,在项目的每个控制器必须从DefaultController继承,而不是控制。在类的构造函数,我加载所有数据共同为整个项目,像这样:
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.
这篇关于MVC3 - 最佳实践来处理所需要的(几乎)所有请求的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!