Mvc3 - Best practice to deal with data which are r

2019-03-31 19:35发布

问题:

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

回答1:

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.



回答2:

I do the same as @rdumont but with one exception: I create a CommonViewModel which I use to define all common properties that I use.

public class CommonViewModel
{
    public string UserName {get;set;}
    public string Extension {get;set; }
}

Declare a property in the base controller:

public abstract class BaseController : Controller
{
    protected CommonViewModel Commons { get; private set; }

    protected virtual void OnResultExecuting(ResultExecutingContext filterContext)
    {
        ViewBag.Commons = Commons;
    }
}

By doing so I get everything almost typed. The only cast that I need to do is to cast ViewBag.Commons to the CommonViewModel.



回答3:

Best is to avoid ViewBag at all.

See this answer, which details how to use Html.RenderAction() for that purpose:

Best way to show account information in layout file in MVC3



回答4:

I'd suggest using a base ViewModel class. So a base class with properties/functions which should be available at any point.