tags:

views:

398

answers:

1

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>" %>

<%=Model.baseurl %>

Finally in Site.Master I added this to where I wanted the menu to show:

<%Html.RenderPartial("ViewGlobalMenu", (MyApp.Web.Models.GlobalMenu)ViewData["menudata"]); %>
+1  A: 

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.

tvanfosson
Worked like a snap...thanks! Adding my sample code above.
Webjedi
Until you forget to derive all of your controllers from the base controller. I'm currently looking at a solution that reads the Properties object within an HttpModule or HttpHandler.
belugabob
@belugabob -- that's why we test.
tvanfosson
:-) Well said...
belugabob