Provide user object to every view - asp.net-mvc

How can I provide a user object to every view in ASP.NET MVC without having to create a ViewModel for absolutely every view I have?
When using ASP.NET Membership, I just get a Profile variable in the views with the profile information, but when rolling my own I don't see a way to export that information.

Inherit your controllers from base controller. In base controller override OnActionExecuting and set ViewData["UserObject"] here. Something like this:
public class YourBaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewData["UserObject"] = ...
}
}
Or create custom filter with the same OnActionExecuting method if you want only certain controllers providing user object to View.
UPDATED:
Create custom Html helper if you dont want to cast ViewData["UserObject"] every time:
public static object RenderUserObject(this HtmlHelper html)
{
return ((html.ViewData["UserObject"] as UserObject) ?? new UserObject()).ToString();
}

Inherit your ViewModel classes from a master ViewModel with a User property.
Alternatively, you can pass the object in ViewData collection and use an extension method to make it easy to access the object in the view.

One alternative to having a base ViewModel class, and so having to define a ViewModel class for every view, is to create a generic ViewModel<T> class which exposes a property T InnerModel, or something similar. Then you can pass a ViewModel<Foo> rather than having to explicitly create a FooViewModel class.
Of course if you also need more bespoke ViewModels in places, you can keep the ViewModel base class, and have ViewModel<T> and your bespoke ViewModels extend it.

Related

MVC - How to instantiate, store and make a typed variable available throughout the application, once per page view

I am developing an MVC app to serve multiple domains - each is a branch of a larger company.
A LocalBranch class stores details such as phone, address, email, location coordinates etc.
I want to create a single instance of this class per http request and have it available throughout the application - from within controllers, views, some helper classes and other code.
Is there a recommended way of doing this?
Right now I have it as a property on a BaseController and use ViewBagto pass it to views. But I would prefer it strongly typed in Views if possible.
I don't want to put it in an application variable, because we need to serve different values to different domains.
I would rather avoid a session variable if possible because we might scale up to use multiple servers in the future, and I've heard this doesn't play well with sessions.
Please feel free to update tags / title if you think there is a clearer way of expressing what I'm after. Thank you.
The best way to maintain your state in a web application per request is simply use the HttpContext class.
You need to store your state(LocalBranch) as an Item in the HttpContext:
HttpContext.Current.Items.Add("LocalBranch", GetLocalBranch());
You can fetch the Item all across your application like this:
LocalBranch branch = HttpContext.Current.Items["LocalBranch"] as LocalBranch;
The Items property is simply a key value Dictionary. The value is an object. You will have to check for nulls and this is really similar to the Session object you know. The main difference is the scope. The HttpContext is a dot net object that has a lifetime of an http request.
Now using the HttpContext the way I've shown you is the simplest way to do it.
You can go two steps forward and use a framework called Unity and add a lifetime to your objects.
Unity does much more and the lifetime management is just one gem.
You can create a custom HttpContext lifetime that generates objects per request. Something like this.
And them all you need to do is:
1.Register you LocalBranch class with the HttpContext lifetime.
2.Add a static Current property which will use the Unity container and resolve the correct instance of LocalBranch.
3.Use it something like this: LocalBranch.Current
BTW, you can use Unity's dependency injection for injecting objects into controllers and other modules. That's a better practice then just using the static Current property.
You kind of have two questions here. The first is "How do I create a single instance of this class per HttpRequest?" The second is "How do I make this available to strongly typed views?"
The first has pretty much been answered by #amir-popovich to use dependency injection. However, FWIW I would probably use Ninject instead of Unity (just preference, really) and I would probably implement it differently. I would not use HttpContext, and simply build a service (which is instanciated using Ninject's OnePerHttpRequest Module, passing the domain as an argument to get the proper values).
Then, in order to add these LocalBranch values to your strongly typed View Model, you can first create a base view model which holds this type:
public class BaseViewModel
{
public LocalBranch Branch {get;set;}
}
Then, make all of your current view models inherit this base type
public MyViewModel : BaseViewModel
{
public string SomeValue {get;set;}
}
Then in your controller, it is easy enough to add these values from the service you created from the first step
public ActionResult SomeAction()
{
var vm = new MyViewModel();
vm.Branch = LocalBranchService.GetLocalBranchValues(); //Local Branch Service has been injected with Ninject
//do other stuff
return View(vm);
}
However, that gets pretty tedious to add that to each controller action, so you can instead create a Result Filter to add it for you:
public class LocalBranchResultFilter : FilterAttribute, IResultFilter
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
//This method gets invoked before the ActionResult is executed.
filterContext.Controller.ViewData.Model.Branch = LocalBranchService.GetLocalBranchValues(); //Local Branch Service has been injected with Ninject
}
}
Now, you can just decorate your Controller and/or Actions with the filter (you could even set it in the Global Filters if you want).
You can embed the child actions into your layout or a view. You can even cache its output so you don't keep re-querying the database.
controller
[ChildActionOnly]
[OutputCache(Duration=500, VaryByParam="*")]
public ActionResult Info()
{
var localBranch = db.GetLocalBranch();
return PartialView("_Info", localBranch);
}
_Info view
This bit will get inserted into your other views
#model LocalBranch
<span>#Model.address</span>
<span>#Model.phone</span>
Use in _Layout or other view
<p>lorem ipsum...</p>
#Html.Action("Info")

BaseViewModel for every Request

Is there a way that I can pass the same BaseViewModel for every request without returning either the BaseViewModel or something that inherits from the BaseViewModel for each view? I'm using a shared view (_layout.cshtml).
No, there isn't a way. If your view or layout is strongly typed to a class BaseViewModel you need to return an instance of this class (or a derived class) from each controller action that is rendering this view.
As an alternative to the base view model approach you may checkout the Html.Action helper in order to encapsulate some common view functionality.

Reusable Content Box Data In ASP.NET MVC?

If I create a PartialView for a box that holds a header, image and content what is the best way to store the content without using a database?
Example: TurboTax
I doubt the content for the boxes in the sidebar are stored in a database but to make reusable code it would be beneficial to create the structure in a PartialView and populate the content areas. I can create a PartialView and pass a Model from the parent Controller to the PartialView but then I would be stuck copying and pasting that same content if I wanted to use the same box on another page.
For fixed content you might want to think about using XML+XSLT or even HTML snippets in the file system and simply rendering them. An HtmlHelper method might make more sense for this than a partial view - Html.RenderXml() or Html.Include(). The only real difference between these and partial views is that the view engine isn't invoked since there aren't any substitutions. I do this sort of thing with my privacy policy and terms and conditions. I'd certainly consider keeping these cached.
If these really are templates and you are just substituting content, then I think the partial view works well and I would consider putting the data in a database, again, maybe using caching if I found that performance suffered. You could use this in combination with the former -- say keep your images/xml in the file system and a pointer to them in the database so you know which ones to pick in the partial.
Passing data to partial view that is used in many places can be done in many ways:
Create base model class for all your models. In base class define PartialModel property which will be holding model for partial view (there may be many of them if use have many partial views). Now you can populate the PartialModel property in controller action, but to make code more reusable you can create your own Action Filter which will insert the partial view data just after the action method is executed (but before the model is passed to the view)
public class PartialViewModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
BaseViewModel model;
if (filterContext.Controller.ViewData.Model == null)
{
model = new BaseViewModel();
filterContext.Controller.ViewData.Model = model;
}
else
{
model = filterContext.Controller.ViewData.Model as BaseViewModel;
}
model.PartialModel = new PartialModel(...) // Partial model initialization
base.OnActionExecuted(filterContext);
}
}
Then you can use it like:
[PartialViewModel]
public ActionResult Index()
{
//...
}
Another option: you can create BaseController class for all your controllers and create PartialModel on base controller initialization. Then PartialModel can be stored in ViewData[] dictionary. Because using ViewData dictionary in views is bad, create extension method on HtmlHelper like:
public static PartialModel GetPartialModel(this HtmlHelper helper)
{
return helper.viewContext.ViewData["PartialModel"] as PartialModel
}
So you could obtaint the model this way:
<% Html.RenderPartial("MyPartial", Html.GetPartialModel()); %>

ASP.NET MVC - Set ViewData for masterpage in base controller

I'm using a masterpage in my ASP.NET MVC project. This masterpage expects some ViewData to be present, which displays this on every page.
If I don't set this ViewData key in my controllers, I get an error that it can't find it. However, I don't want to set the ViewData in every controller (I don't want to say ViewData["foo"] = GetFoo(); in every controller).
So, I was thinking of setting this in a base controller, and have every controller inherit from this base controller. In the base controller default constructur, I set the ViewData. I found a similar approach here: http://www.asp.net/learn/MVC/tutorial-13-cs.aspx. So far so good, this works... but the problem is that this data comes from a database somewhere.
Now when I want to Unit Test my controllers, the ones that inherit from the base controller call its default constructor. In the default constructor, I initialize my repository class to get this data from the database. Result: my unit tests fail, since it can't access the data (and I certainly don't want them to access this data).
I also don't want to pass the correct Repository (or DataContext, whatever you name it) class to every controller which in turn pass it to the default controller, which I could then mock with my unit tests. The controllers in turn rely on other repository classes, and I would end up passing multiple parameters to the constructor. Too much work for my feeling, or am I wrong? Is there another solution?
I've tried using StructureMap but in the end I didn't feel like that is going to fix my problem, since every controller will still have to call the base constructor which will initialize the repository class, so I can't mock it.
This is a similar question but I find no satisfactory answer was given. Can I solve this in a neat way, maybe using StructureMap as a solution? Or should I jsut suck it and pass a Repository to every controller and pass it again to the base controller? Again, It feels like so much work for something so simple. Thanks!
I see two options:
First:
Set the ViewData for MasterPage in YourBaseController.OnActionExecuting() or YourBaseController.OnActionExecuted():
public class YourBaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Optional: Work only for GET request
if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
return;
// Optional: Do not work with AjaxRequests
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
return;
...
filterContext.Controller.ViewData["foo"] = ...
}
}
Second:
Or create custom filter:
public class DataForMasterPageAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Optional: Work only for GET request
if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
return;
// Optional: Do not work with AjaxRequests
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
return;
...
filterContext.Controller.ViewData["foo"] = ...
}
}
and then apply to your controllers:
[DataForMasterPage]
public class YourController : YourBaseController
{
...
}
I think the second solution is exactly for your case.

Accessing Application Settings in ASP.NET MVC view

I'm trying to build a global menu into my ASP.NET MVC site.master, and I was wondering how I could go about accessing the Application Settings property from the site.master markup? Previously I probably would have instantiated a config object from my site.master's code-behind and then set a public property. But now I'm scratching my head...must need more coffee.
UPDATED with answer code
Added a string setting to the application propererties called baseurl and gave it a value of "http://mysite.com"
Made a model class of GlobalMenu.cs
public class GlobalMenu
{
private string _baseurl;
public string baseurl
{
get { return _baseurl; }
set
{
_baseurl = value;
}
}
}
Created a base controller class named BaseController and inherited from Controller, and overroad OnActionExecuted thusly:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
string baseurl = Properties.Settings.Default.baseurl;
GlobalMenu menumodel = new GlobalMenu();
menumodel.baseurl = baseurl;
ViewData["menudata"] = menumodel;
base.OnActionExecuted(filterContext);
}
Created a partial view called ViewGlobalMenu in the Shared folder that was strongly typed to GlobalMenu that looks like this...but with more stuff obviously:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Web.Models.GlobalMenu>" %>
Finally in Site.Master I added this to where I wanted the menu to show:
<%Html.RenderPartial("ViewGlobalMenu", (MyApp.Web.Models.GlobalMenu)ViewData["menudata"]); %>
Here's the strategy that I would probably use. Create a base controller from which your other controller's will derive and have it derive from Controller. Override the ActionExecuted method in the base controller and have it access the application settings (and probably cache them). Generate ViewData for your menu as strongly-typed menu model class assigned to a particular key in the ViewData. You only need to provide the model to actions that are returning a ViewResult (and, perhaps, PartialViewResults).
Create a strongly-typed partial view that implements the global menu markup using the menu model class. Include this in the MasterPage definition via RenderPartial. Pass the ViewData item corresponding to the key as the Model to the partial view so that you can use the model's properties in your menu.
This should do the trick from within the View -->
#System.Configuration.ConfigurationManager.AppSettings["AppSetting"]

Resources