开发者

ASP.NET MVC: How to handle model data that must go to every view?

So if there is some global state that every view of an MVC app will need to render ... for example: IsUserLoggedOn and UserName ... whats开发者_Go百科 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?


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 - see the answer to a similar question asked at exactly the same time as this:

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...


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>"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜