CONNECT WITH US

Featured Post

ASP.NET MVC: Accessing base controller from view

Get article update by Email

Today, I was examining one ASP.NET MVC application for code optimization. And at the same time as a part of code rearrangement, I required to access base controller instance from view. So here in this post we will see how we can access base controller instance from within view. Before looking at actual implementation, let me describe how all controller were arranged.

Controller structure

In MVC application, we had one controller named BaseController derived from System.Web.Mvc.Controller and all other application controller were derived from this BaseController so we can have hook in case if we require to plug some logic or extend all controller at later time. Following is pseudo code for the same.

public class BaseController : Controller
{
    private string _userRole;
 
    public string UserRole
    {
        get { return _userRole; }
    }
}
 
public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }
}

In above pseudo code, for illustrative purpose we have put one property which expose role of logged in user. From within controller, we can access it with this.UserRole but we cannot access it directly from view.

As we can see in above image that we can access ControllerBase with @ViewContext.Controller but we can’t access our base controller directly. However we can cast @ViewContext.Controller in BaseController because our BaseController is inherited from System.Web.Mvc.Controller which is again inherited from ControllerBase class. But each time casting @ViewContext.Controller is not good way better we create extension method which cast it and return BaseController instance. So below is the code which adds extension method to ViewContext class.

public static class ViewContextExtension
{
    public static BaseController BaseController(this ViewContext view)
    {
        BaseController baseController = (BaseController)view.Controller;
        return baseController;
    }
}

Once we add above code we can access base controller with @ViewContext.BaseController() and hence we can also access @ViewContext.BaseController().UserRole and all other member of base controller from view. Hope this would be hopeful!

You can follow me on twitter for latest link and update on ASP.NET & MVC.

3 comments:

Anonymous said...

Why are you accessing the controller from the view in the first place? You can just pass all the needed data via your model, which makes it much more transparent which data is used in which view and separates your V from your C...

Darren Sherwood said...

I can see this being useful for cross cutting concerns. For example looking up custom text strings for the user via a simple key, value GetText method that identifies the user via session data.

Darren Sherwood said...

While normally your right, there are times when it is useful...

Post a Comment