Anonymous Creator
Anonymous Creator

Reputation: 3789

Common Index Action for all controller

Currently to return view, I have to write one method in all the controllers. That is "Index" action method. It has nothing to do except returning their respective views.

So is it possible to make them common?

I have inherited one common basecontroller which is inherited from apicontroller. So is there a way that I write base index method. and i can override it as well if needed?

Upvotes: 0

Views: 590

Answers (1)

Mohsin Mehmood
Mohsin Mehmood

Reputation: 4236

You can create a BaseController class like this:

  public class BaseController : Controller
    {
        public virtual IActionResult Index()
        {
            return View();
        }
    }

Then inherit your controller clasess from base controller:

public class CustomersController : BaseController
    {

    }

You can override the Index method like this:

 public class HomeController : BaseController
{
    public override IActionResult Index()
    {

        return View("About");
    }
}

Upvotes: 2

Related Questions