tags:

views:

67

answers:

2

In almost every page in my ASP.NET MVC site I am using information about the user. This is usually pulling in information about the company they work for in the Model to pass through to the view, or in the View to establish which parts of the page the user can view with their permissions.

Instead of getting the User in every Model, is there a way to easily have the User data available all the time? I.e. should I set up a base model, or have some 'master' controller that passes the user through in ViewData?

Any thoughts, or even better any code would be greatly appreciated.

+4  A: 

It is a great idea. I use a MasterModel consistently in all my MVC projects.

For this to work you need to subclass all your view models and also strongly type your MasterPage to MasterModel.

public class MasterModel
{
    string UserName { get; set; }
}

public class HomeModel : MasterModel
{
}

public class NewsModel : MasterModel
{
}

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<MasterModel>" %>

User name: <%= Model.UserName %>
Developer Art
+1 I can't imagine the amount of pain I would go through without having one.
Kevin
Fantastic, makes life much easier.
h_a_z_
A: 

It's a good idea so long as you're not reinventing the wheel. Quite a bit of information which people often put in view models (notably, here, the ASP.NET user, but people also seem to duplicate the route data a lot) is already available to the view without adding it to the model. But for things which aren't already in the view it's fine.

Craig Stuntz