Last Updated: September 30, 2021
·
51.84K
· ordepdev

BaseController in ASP.NET MVC

Instead of repeating common actions on your code try to implement abstract classes to do the job.

Every controller in ASP.NET MVC deals with TempMessages, ViewBags, new instances of classes and many more.

Why don't you create a base Controller that implements this common actions and can be accessible by all the derived controllers?

Something like this:

public abstract partial class BaseController : Controller
{
    public UnitOfWork unitOfWork;

    public BaseController()
    {
        unitOfWork = new UnitOfWork();
    }

    public String ErrorMessage
    {
        get { return TempData["ErrorMessage"] == null ? String.Empty : TempData["ErrorMessage"].ToString(); }
        set { TempData["ErrorMessage"] = value; }
    }
}

And can be used like this:

public partial class HomeController : BaseSecuredController
{
    public KioskController() 
        : base()
    { 
    }

    public virtual ActionResult Index()
    {
        try 
        {
            var result = unitOfWork.DoSomething();
        }
        catch(Exception ex)
        {
            ErrorMessage = "Ooops, something went wrong: " + ex.Message;
        }
        return View();         
    }
}

Pretty much cleaner don't you think? Do you use this kind of method? Some people have afraid of "strange" modifiers like abstract or partial.