Need:

To pass information to every view based on an environmental variable. The specific case I ran across this need is when you want to use the minified version of your JavaScript libraries in production and the human readable in dev/QA.

Solution:

  • Create your own base controller class.
  • Override either onactionexecuting or onactionexecuted.
  • Populate TempData with the environment specific information.
  • Change your controllers to inherit from your custom base controller
  • Use that information in the view.
using System.Configuration;using System.Web.Mvc;

namespace BaseController.Controllers{    public class BaseController : Controller    {        protected override void OnActionExecuting(ActionExecutingContext filterContext)        {

            filterContext.Controller.TempData["OnActionExecuting"] = "OnActionExecuting";            filterContext.Controller.TempData["js_dev"] = ConfigurationManager.AppSettings["js_dev"];

            base.OnActionExecuting(filterContext);        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)        {

            filterContext.Controller.TempData["OnActionExecuted"] = "OnActionExecuted";            filterContext.Controller.TempData["js_prod"] = ConfigurationManager.AppSettings["js_prod"];            base.OnActionExecuted(filterContext);        }    }}

Pros:

  • I’ve found that I often have to create my own base controller class. Doing so for something this simple is a god starting point.

Cons:

Alternate Solutions:

  • Use T4 templates to generate a const file based on environment.
  • Put the information of each server in the machine.config

Final:

The solution is sound and a sample is attached but I am going to have to come back and flesh out this post a little more with details about the *.config/caching and other options.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2012 eric.polerecky.com Suffusion theme by Sayontan Sinha