views:

44

answers:

3

So if there is some global state that every view of an MVC app will need to render ... for example: IsUserLoggedOn and UserName ... whats the appropriate way of getting that information to every view?

I understand that that part of the view should be in the master page or in a partial view thats added to the other views. But whats a good way to make sure the 'global' model data is passed to the view every time from all the relevant controllers and actions?

+3  A: 

codeulike - see the answer to a similar question asked at exactly the same time as this:

http://stackoverflow.com/questions/4036582/asp-net-mvc-displaying-user-name-from-a-profile

in a nutshell, basically create a base controller that's inherited by all your other controllers. the base controller then has an override function that carries thro' to all 'child' controllers. rather than duplicate the code, take a look at my answer above and give it a try..

cheers...

jim
+1  A: 

You could create base class for viewmodel which contains shared information and inherit that for each viewmodel.

public class ViewModelBase
{
    // shared data
}
public class Page1ViewModel : ViewModelBase
{
    // page 1 data
}

In masterpage you could use that base class

Inherits="System.Web.Mvc.ViewMasterPage<ViewModelBase>"

and in each view use those derived classes

Inherits="System.Web.Mvc.ViewPage<Page1ViewModel>"
Mika Kolari
Right, but how do I populate that viewmodel every time? Presumably with a base controller, right?
codeulike
ViewModelBase constructor/helper class/controller base class
Mika Kolari
+2  A: 

After asking this, I found this good blog post by Steve Sanderson: http://blog.stevensanderson.com/2008/10/14/partial-requests-in-aspnet-mvc/

He suggests three different approaches:

  • Use a base controller class or ActionFilter to add the relevant model to the ViewData[] collection every time. I think a few people have suggested that sort of thing already.

  • Use Html.RenderAction() in the view ... and as he says:

If someone tells you that internal subrequests are bad because it “isn’t MVC”, then just bite them on the face immediately. Also ask them why they’re still willing to use Ajax, and even <IMG> tags for that matter, given that both are a form of subrequest.

  • Use 'Partial Requests' (he provides the code for this on his blog) which allow one controller to nest calls to other controllers into a sortof nested ViewData structure.
codeulike
+1 RenderAction is the way to go. Keeps nice SRP
redsquare