@Blog.Author(Nandip Makwana) .LearningExperience(ASP.NET, ASP.NET MVC, IIS, jQuery & Technology Surrounding it...)

December 22, 2012 comment

ASP.NET MVC: Accessing base controller from view

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.

comments powered by Disqus

Featured Content

Resources & Tools

About Nandip Makwana

Nandip Makwana is passionate about digital world and web. He completed his Masters in Computer Application in June 2011. Currently he is working as a Software Engineer. He has shown great promise and command over ASP.NET and technologies surrounding it during his academic years and professorial life...continue reading