Note that there are some explanatory texts on larger screens.

plurals
  1. POView Models (ViewData), UserControls/Partials and Global variables - best practice?
    primarykey
    data
    text
    <p>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.</p> <p>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?</p> <p>If I have a simple partial that needs to display a blog post then it looks like this:</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" Inherits="ViewUserControl&lt;Post&gt;" %&gt; </code></pre> <p>and simple code to render this partial in my view (that its model.Posts is <code>IEnumerable&lt;Post&gt;</code>):</p> <pre><code>&lt;%foreach (Post p in this.Model.Posts) {%&gt; &lt;%Html.RenderPartial("Post",p); %&gt; &lt;%}%&gt; </code></pre> <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:</p> <pre><code>&lt;%Html.RenderPartial("Post",new PostViewData { Post=p,CurrentUser=Model.CurrentUser,... }); %&gt; </code></pre> <p>Or I could use a copy constructor</p> <pre><code>&lt;%Html.RenderPartial("Post",new PostViewData(Model) { Post=p }); %&gt; </code></pre> <p>I just wonder if there's any other way to implement this before I move on.</p> <p>Any suggestions?</p> <p>Thanks! </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload