View Models (ViewData), UserControls/Partials and Global variables - best practice?

Posted by elado on Stack Overflow See other posts from Stack Overflow or by elado
Published on 2009-06-24T13:21:14Z Indexed on 2010/05/02 2:07 UTC
Read the original article Hit count: 286

Hi

I'm trying to figure out a good way to have 'global' members (such as CurrentUser, Theme etc.) in all of my partials as well as in my views.

I don't want to have a logic class that can return this data (like BL.CurrentUser) I do think it needs to be a part of the Model in my views So I tried inheriting from BaseViewData with these members. In my controllers, in this way or another (a filter or base method in my BaseController), I create an instance of the inheriting class and pass it as a view data. Everything's perfect till this point, cause then I have my view data available on the main View with the base members. But what about partials?

If I have a simple partial that needs to display a blog post then it looks like this:

<%@ Control Language="C#" AutoEventWireup="true" Inherits="ViewUserControl<Post>" %>

and simple code to render this partial in my view (that its model.Posts is IEnumerable<Post>):

<%foreach (Post p in this.Model.Posts) {%>
    <%Html.RenderPartial("Post",p); %>
<%}%>

Since the partial's Model isn't BaseViewData, I don't have access to those properties. Hence, I tried to make a class named PostViewData which inherits from BaseViewData, but then my containing views will have a code to actually create the PostViewData in them in order to pass it to the partial:

<%Html.RenderPartial("Post",new PostViewData { Post=p,CurrentUser=Model.CurrentUser,... }); %>

Or I could use a copy constructor

<%Html.RenderPartial("Post",new PostViewData(Model) { Post=p }); %>

I just wonder if there's any other way to implement this before I move on.

Any suggestions?

Thanks!

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about viewdata