This is a mirror of official site: http://jasper-net.blogspot.com/

Passing Configuration Data to the Master Page in ASP.NET MVC

| Wednesday, November 24, 2010
One of the common activities that I have found myself doing lately whenever I create a new project is to identify a way of loading configuration information and customizing the behavior of the Master Page. The way I initially went about solving this problem was to create a base class and have all of my Page ViewModel’s inherit from it. This caused two different things that I had to constantly maintain, making sure all of my ViewModel’s inherited from this MasterViewModel and then remembering to set the data every time a ViewResult is returned in an Action.

public class MasterViewModel : IMasterViewModel
{
   public string SiteName { get; set; }
}

I was able to take care of the second concern by simply creating a base controller that all of my controllers would inherit from and then override View(string viewName, string masterName, object model) { … } so that the settings are automatically injected into the model.

protected override ViewResult View(string viewName, string masterName, object model)
{
   ((MasterViewModel)model).SiteName = "Example";
   return base.View(viewName, masterName, model);
}

In order to get around the smell of forcing my ViewModel’s to inherit from a base class I put the MasterViewModel into the ViewData dictionary that is returned in the ViewResult.

protected override ViewResult View(string viewName, string masterName, object model)
{
   ViewResult result = base.View(viewName, masterName, model);
   result.ViewData[Data.Site] = _blogConfiguration.Configuration;
   return result;
}


Read more: about:thoughts

Posted via email from .NET Info

0 comments: