Search code examples
c#asp.net-mvc

What is the Index method inside of a controller?


I'm following this tutorial on how to develop unit tests using xUnit for .Net application. On this video he is developing tests on a controller and there is a method called Index inside this controller, and the way he speaks of this method makes it look like it is a common practice to have one method with that name in a controller.

Index makes me think of the Index page from websites but I don't remember hearing anything about methods called Index inside Controllers.

By the way, I am familiarized with MVC design pattern but I learned things on the go on my old job and never stopped to fully understand what I was doing.


Solution

  • Index is an action that you have to write, just like any other action. What makes Index special is that it is the default action for a controller.

    For instance, let's say that you have a ThingController and it has actions named Index and Stuff. To access the latter, you would have to use the URL "www.example.com/thing/stuff". To access the former, you could use the URL "www.example.com/thing/index" in the same way, but you could also use "www.example.com/thing" for the same effect. If a URL specifies a controller but not an action, the action defaults to Index. Other than that, Index is exactly like any other action.

    For that reason, Index usually contains what you would consider to be the default functionality for that controller, e.g. displaying a list or search page for the corresponding entity. If there is nothing that you would consider to be default functionality, it's possible that you might choose not to include an Index action. You don't need to, but most controllers will have one.