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

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!

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.

Related

Can a controller influence the _layout.cshtml file?

I'm stuck! I'm under the impression that the _layout.cshtml file is used for MasterPage-like content. Everything there is rendered on every page. Naturally, I want to write the code for rendering my sidebar menu in that file.
I want to dynamically display a list of Categories from my DB, but I'm having a problem with passing the actual model of categories to Layout.cshtml since it seems no controller actually touches it.
Any suggestions?
Otherwise please tell me how to approach this problem. I've been wracking my brain for the past three days and still no elegant solution.
I need to:
Dynamically fetch a list of Categories from the DB.
Display this list of Categories on every single view. (Hence the use of _layout.cshtml)
Elegantly handle each different categories click.
I'm at my wits end. :P How would you solve this?
_layout.cshtml
#if(isSectionDefined("Categories"))
{
<div id="sidebar">
#RenderSection("Categories", required: false )
</div>
}
index.cshtml
#section Categories {
<ul>
<li>Category One</li>
<li>Category Two</li>
<li>Category Three</li>
</ul>
}
see this : http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
Any viewmodel that you pass to your view is automatically available within your master page. If you do not use RenderAction/Action which is the best approach, then you must create the necessary master page data in every action and add it to viewdata - either by having a common base class for your strongly typed viewmodel that contains all master page data or by using the viewdata dictionary.
I would strongly recommend that you go down the html.action approach though. In this way, you have a totally separate controller action for dealing with your list of categories. This action can retrieve the neccesary category data and return the categorylist usercontrol as a partialview and you will not have to worry about polluting all your other actions with this data.
As I see it, ViewData (and its relatives like ViewBag, Model, etc.) is meant for the specific current view. Your _Layout.cshtml is not specific to the current view; and it would be awkward if EVERY controller would have to pass the categories data in addition to whatever else data it needs to pass for the view.
Instead, what I do, is provide a static method in one of my helper classes that retrieves the categories from the DB. I also do some caching there, so that I do not have to hit the DB on every single request. The _Layout.cshtml then simply calls this static method. Simple and elegant.
If you wish, you can bring this out to a partial view, make it a helper method, whatever.
One note of caution though - my custom error view also uses the same _Layout.cshtml, and if the DB goes down, you get an exception trying to display the exception. ASP.NET MVC is smart enough to detect this and abort processing, but you're left with a nondescript default error page. What I did was to place try...catch statements around these dangerous calls, which quietly ignore the exception if the current page is the error view.
I've achieved something similar by having my ViewModels implement an Interface which has members that contain the menu data. In my action method I set that data. Then in my view I check to see if my view-model implements that inteface, pull the menu data out and render the menu (in a partial view actually)

Pass data to User Control ASP.NET MVC

I have a user control which shows list of latest announcements. This user control would be used in almost 90% of my pages. Now my concern is how to pass data to this user control for latest announcements.
My first approach is to make a base controller and in Initialise method I pass data to user control via ViewBag/ViewData. All my other controllers derive from this base controller. This looks nice but my concern is that it may become an overkill for some simple solution existing already out there. Also I would need to make sure that no controller ever fiddles with my Viewdata/Viewbag data meant for my usercontrol.
Please let me know if this is correct way of proceeding ahead or there exists some better solution.
Thanks
Assuming you have a "user control" (you should try to refer to them as partial view's in MVC) that looks like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Announcement>>" %>
This means your partial view expects a list of Announcement objects.
Now, the question is - where are you rendering this partial view?
You could be doing it from a master page, you could be doing it from a view, or you could be doing it from another partial view.
Either way, the code to render the partial needs to look like this:
<% Html.RenderPartial("LatestAnnouncements", announcements) %>
But - where do you get the announcements from.
Assuming you have a Repository/DAL/helper method to get the latest announcements - i think you should have the ViewModel's you require inheriting from a base ViewModel:
public class AnnouncementViewModelBase
{
protected IEnumerable<Announcement> GetAnnouncements()
{
// call DAL
}
}
Then any master/view/partial that needs to render the latest announcements partial should be bound to a ViewModel which inherits from that base view model.
In the cases where the master/view/partial is not strongly-typed (e.g dynamic view), you can stick it in the ViewData. But if you have organized your view's correctly this shouldn't be required.
Is this the kind of thing you're after? How to pass data from view to UserControl in ASP.NET MVC?
You should use RenderAction in this kind of scenario, so that you do not have bother to pass the required data in each action method of your controllers.
I think the best way would be to use #Html.Action. This would allow me to call my actions dedicated to my usercontrols data and I can call it from anywhere.

Encapsulating User Controls in ASP.NET MVC

Sorry if this is a basic question - I'm having some trouble making the mental transition to ASP.NET MVC from the page framework.
In the page framework, I often use ASCX files to create small, encapsulated chunks of functionality which get inclded in various places throughout a site. If I'm building a page and I need one of these controls - I just add a reference and everything just works.
As far as I can tell, in MVC, the ASCX file is just a partial view. Does this mean that wherever I want to add one of these units of functionality I also have to add some code to the controller's action method to make sure the relevant ViewData is available to the ASCX?
If this is the case, it seems like a bit of a step backwards to me. It means, for example, that I couldn't just 'drop' a control into a master page without having to add code to every controller whose views use that master page!
I suspect I'm missing something - any help would be appreciated.
Thanks,
- Chris
As far as I can tell, in MVC, the ASCX
file is just a partial view. Does this
mean that wherever I want to add one
of these units of functionality I also
have to add some code to the
controller's action method to make
sure the relevant ViewData is
available to the ASCX?
Yes.
However, you can use a RenderAction method in your view instead of RenderPartial, and all of your functionality (including the data being passed to the sub-view) will be encapsulated.
In other words, this will create a little package that incorporates a controller method, view data, and a partial view, which can be called with one line of code from within your main view.
Your question has been answered already, but just for sake of completeness, there's another option you might find attractive sometimes.
Have you seen how "controls" are masked on ASP.NET MVC? They are methods of the "HtmlHelper". If you want a textbox bound to "FirstName", for example, you can do:
<%= Html.Textbox("FirstName") %>
And you have things like that for many standard controls.
What you can do is create your own methods like that. To create your own method, you have to create an extension method on the HtmlHelper class, like this:
public static class HtmlHelperExtensions
{
public static string Bold(this HtmlHelper html, string text)
{
return "<b>" + text + "</b>\n";
}
}
Then in your view, after opening the namespace containing this class definition, you can use it like this:
<%= Html.Bold("This text will be in bold-face!") %>
Well, this is not particularly useful. But you can do very interesting things. One I use quite often is a method that takes an enumeration and created a Drop Down List with the values from this enumeration (ex: enum Gender { Male, Female }, and in the view something like Gender: <%= Html.EnumDropDown(Model.Gender) %>).
Good luck!
You can render a partial view and pass a model object to.
<% Html.RenderPartial("MyPartial", ViewData["SomeObject"]);
In your partial view (.ascx) file, you can then use the "Model" object (assuming you've inherited the proper object in your # Control deceleration) to do whatever you need to with that object.
You can, ofcourse, not pass and Model and just take the partial view's text and place it where you want it.
In your main view (.aspx file), you will need to define the proper object in the ViewData that you're passing to the partial view.
Another method you can do is use:
<% Html.RenderAction("MyAction", "MyController", new { Parameter1="Value1"}) %>
What the previous method does is call a controller Action, take its response, and place it where you called the "RenderAction()" method. Its the equivalent of running a request against a controller action and reading the response, except you place the response in another file.
Google "renderaction and renderpartial" for some more information.

Populating the model for a shared view, embedding a shared view within another view

I'm trying to embed a small view snippet that steps through a model fragment that works fine when I embed it in a single controller and pass it to a view like so;
Controller:
return View(_entities.formTemplate.ToList());
View:
http://www.pastie.org/666366
The thing is that I want to be able to embed this particular select box in more than just this single action / view, from the googling I've been doing this appears that it should go into a shared view, but I'm not clear then on how I could populate the model within that view from the controller? (or maybe I'm completely missing the purpose for shared views?)
In the other MVC framework I'm accustomed to working with there is the concept of a filter where you can call code before or after any action and mod the model as it passes the controller and goes to the view, is such a thing possible in .net mvc?
Any assistance appreciated.
You'll want to use the HtmlHelper method DropDownList() in order to create a input:
<%= Html.DropDownList("id", new SelectList(formBuilder, "ID", "Name")) %>
You probably want to use a ViewUserControl here.
You have a couple of options if you go that route. If it's model data that is easily available, recreate it at the call site of your RenderPartial like so:
<%=Html.RenderPartial("ViewName", new ModelData())%>
If it's data that is dependent on the current model data, then you'll need to pass that data somehow to your partial view.
ASP.Net MVC also has the concept of before/after controller actions. You decorate your controller method with an Attribute that derives from ActionFilterAttribute. In there, you have access to OnActionExecuting and OnActionExecuted.

Duplicating code in MVC controllers

I think I have a problem in understanding the proper way of using MVC. The problem I'm having is that I have Users and Admin Users, both are allowed to create a campaign but they are using different master pages etc etc.
My solution so far is...
Controllers
AdminUserController.cs
UserController.cs
Views
AdminUser
CreateCampaign.aspx
User
CreateCampaign.aspx
But in doing it in this way I'm having to duplicate the CreateCampaign() code in both the AdminUserController and the UserController and I have 2 views to do the same thing.
Is this the right way of doing it or am I missing the boat somewhere?
Extract the common code to a base controller from which both inherit. Extract the shared view to a common, shared partial view (ViewUserControl), then have each view include this shared partial. The latter is really only necessary since your view uses different master pages.
Controllers:
BaseUserController
CreateCampaign()
UserController : BaseUserController
AdminController : BaseUserController
Views:
Shared
CreateCampaignShared.ascx
Admin.Master
User.Master
Admin
CreateCampaign.aspx -- includes <% Html.RenderPartial( "CreateCampaignShared" ); %>
User
CreateCampaign.aspx -- includes <% Html.RenderPartial( "CreateCampaignShared" ); %>
You can do pretty well with a single controller, leave it to UserController. Admin is just another user, right? In your CreateCampaign() code you can check for "special" status of the logged in user and set some extra properties before saving the data.
Whether you can get away with a shared view depends on how much they vary. You can use simple IsAdmin() checks in the view to render or not some extra controls. Or you can check it in the controller and serve one view or another.
Why do you have two different "Users"? I'd prefer one user-Class and roles to provide access to different views / actions
Then you would create a Campain-Controller and there a CreateCampaign-Action.
You're missing the partial boat :)
You can create one CreateCampaign.ascx file that shares the common view code and call it as a partial view in some other view. Instead of creating full views, create a partial view (an .ascx file), and have it contain the duplicate code and markup.
Then you can re-use it in other views with this:
<% Html.RenderPartial("CreateCampaign") %>
Re-use your controller code by factoring it out into some base controller which your specific controllers inherit from.
How about having a CampaignController that has the Create method which then displays different views depending on the type of user. Something like:
public class CampaignController : Controller {
public ActionResult Create() {
//...
if (User.IsInRole("Admin") {
Return View("AdminUser/CreateCampaign");
}
else {
Return View("User/CreateCampaign");
}
}
}
And as others have said the duplicated markup/code in the views should be seperated into partial views and then RenderPartial() used:
<% Html.RenderPartial("Campaign") %>
If it's as simple as displaying a different master to users who are admins you can set the master page to use for the View from the controller as follows:-
return View("CreateCampaign", User.IsInRole("Admin") ? "Admin", "User");
This should allow you to have a single Campaign controller and Create view which seems more natural to me than controllers dedicated to a particular type of user (which sounds like an implementation detail).

Resources