views:

272

answers:

1

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!

A: 

Have you considered keeping these things in the session and writing a strongly-typed wrapper around the session that will give you access to this information? Then in any view you can simply create a new wrapper class with the ViewPage's (or ViewUserControl's) Session property and use it.

tvanfosson
I don't think Session is the solution since it's stored on the server for a long time, but you gave me a new direction to think of: using HttpContext.Current.Items, and let the BaseViewData retrieve the data from there. When an action prepares the ViewData initially, the BaseViewData will store the data in HttpContext.Current.Items (using BaseViewData setters) and when the other partials will access those properties they will be read from the HttpContext.Current.Items (using BaseViewData getters).Still looking for more elegant solution, though this sounds better.Thanks!
elado
Your examples: current user, theme - seem like they would be good candidates to keep for the entire session. Do you have other "global" properties that don't fit this mold?
tvanfosson