C # Centralizing Duplicate VIewData in MVC

When a user logs into my application, I want to show his name in the entire application. I am using asp.net MVC framework. But what I don't want is that you need to add something like to each controller:

ViewData["User"] = Session["User"]; 

This is because you cannot repeat yourself. (I believe this is a DRY [Do Not Repeat Yourself] OO programming principle.) ViewData ["User"] is on my main page. So my question is: what's the neat way to handle my ViewData ["User"] in one place?

+6
c # asp.net-mvc
source share
4 answers

You can do this quite easily either in the base class of the controller or in the action filter that applies to controllers / actions. In any case, you get the opportunity to touch the request before (or after) the action - so you can add this function there.

For example:

 public class UserInfoAttribute : ActionFilterAttribute { public override void OnActionExecuting( ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); filterContext.Controller.ViewData["user"] = "Foo"; } } ... [HandleError, UserInfo] public class HomeController : Controller {...} 

(can also be used at the level of action (method))


or with a common base class:

 public abstract class ControllerBase : Controller { protected override void OnActionExecuting( ActionExecutingContext filterContext) { ViewData["user"] = "Bar"; base.OnActionExecuting(filterContext); } } [HandleError] public class HomeController : ControllerBase {...} 
+12
source share

It has been a year, but I just stumbled upon this question, and I believe that there is a better answer.

Jimmy Bogard describes the solution described in the accepted answer as an anti-pattern and offers the best solution including RenderAction : http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/18/the-filter-viewdata- anti-pattern.aspx

+5
source share

Create a base class for your models with the UserName property:

 public abstract class ModelBase { public string UserName { get; set; } } 

Create a base class for your controllers and override it with the OnActionExecuted method. Inside it, check if the model from BaseModel is looped, and if so, set its UserName property.

 public class ControllerBase : Controller { protected override void OnActionExecuted( ActionExecutedContext filterContext) { var modelBase = ViewData.Model as ModelBase; if (modelBase != null) { modelBase.UserName = "foo"; } base.OnActionExecuted(filterContext); } } 

You can then display the user name in the view as follows:

 <%= Html.Encode(Model.UserName) %> 

See also :

  • Best Practices, Tips, and Tricks for ASP.NET MVC
+2
source share

Another method of providing persistent model data throughout your application is to override the DefaultFactoryController with your custom one. In your CustomerFactoryController, you are wetting the ViewBag with the model you want to keep.

+1
source share

All Articles