Any time you need to show data (on any particular object or collection of objects) on the view, use a strongly typed view.
If your view is purely informational, you may be able to use the ModelState to pass small bits of information (eg: Success/Error pages, Not Authorized Messages, and etc.)
In my applications, I have EVERY view strongly typed, so that I can easily pass user login information to the Master Page. That is, all of my views are strongly typed, templated and constrained to a base class that contains the Site Configuration and the User Login info.
Because of that, I can do this:
public class MyBaseMasterPage : ViewMasterPage<MyBaseModel>
{
public string CurrentTheme
{
get
{
if (this.Model.CurrentUser != null)
return this.Model.CurrentUser.Theme;
else return this.Model.Config.DefaultTheme;
}
}
public User CurrentUser { get { return this.Model.CurrentUser; } }
public ConfigurationRepository Config { get { return this.Model.Config; } }
}
Note that, since the Master Page is themed based on ONLY what is populated in the model, the View itself will never trigger a hit to the database/cache.
MyBaseModel is configured like so:
public class MyBaseModel
{
private MyBaseModel() { }
public MyBaseModel(MyBaseController controller)
{
this.CurrentUser = controller.CurrentUser;
this.Config = controller.Config;
}
public User CurrentUser { get; private set; }
public ConfigurationRepository Config { get; private set; }
}
The private constructor forces all subclasses of my model to initialize the model with the soruce controller.
The controller base class pulls the user out of session and the Config out of cache.
That way, no matter what, all of my views have access to the user and config data, without ever generating a hit to the DB.
Now, in MyBaseController:
public class LanLordzBaseController : Controller
{
[Obsolete]
protected new ViewResult View(string viewName, object model)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
if (!(model is MyBaseModel))
{
throw new ArgumentException("The model you passed is not a valid model.", "model");
}
return base.View(viewName, model);
}
protected ViewResult View(string viewName, MyBaseModelmodel)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
return base.View(viewName, (object)model);
}
public ConfigurationRepository Config { get { ... } }
public User CurrentUser { get { ... } }
}
This helped me find all of my controllers that were returning views that weren't inherited from the proper base class.