tags:

views:

89

answers:

3

In my ASP.Net web sites I have the following code that I am able to use site-wide.
How do I do the same in ASP.Net MVC2?

public class BasePage : Page
{
 public BasePage()
 {
    this.PreInit += new EventHandler(BasePage_PreInit);
 }

 /// <summary>Every page executes this function before anything else.</summary>
 protected void BasePage_PreInit(object sender, EventArgs e)
 {
    // Apply Theme to page
    Page.Theme = "Default";
 }
 public bool IsSiteAdmin(string userName)
 {
    if (System.Web.Security.Roles.IsUserInRole(userName, "SiteAdmin1"))
        return true;
    return false;
 }
}
+2  A: 

MVC has master pages and views. It sounds like you want your Controller to have some base logic in it instead of your page. In your controller you can select a different master page when rendering your views, based on your condition, if you want.

No Refunds No Returns
+2  A: 

Not sure how themes fit into MVC (not very well I suspect), but in general you just need to create a base controller class.

public class BaseController : Controller

and then derive all your controllers off this base.

public class HomeController : BaseController

That way, you can have common functionality available to all controllers. eg your IsSiteAdmin method.

zaph0d
+3  A: 

As zaph0d said, you want to override the Controller class. There are several "events" you can override when creating your own Controller class. A list of those would be here:

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller_members.aspx

Here's what you might want to do. Note that I have no idea what Page.Theme is or does.

public class BaseController : Controller
{
    protected string Theme { get; set; }

    protected override void OnActionExecuting(ActionExecutingContext context)
    {
        Theme = "Default";
    }

    public bool IsSiteAdmin(string userName)
    {
        return System.Web.Security.Roles.IsUserInRole(userName, "SiteAdmin1");
    }
}
Stuart Branham
An alternative to using the OnActionExecuting filter is to make the Theme property lazy-loaded, so that it initializes itself (perhaps from session, or route data, or whatever) on first use. I find that approach easier to understand because it's very clear from the property definition where the value is coming from, and it's just as easy to stub out the value during testing as with the filter.
Seth Petry-Johnson