The main part of a controller class is its action methods.
Action methods are just some public methods that do not return anything and are
marked with a ControllerAction attribute which makes
a method an action method.
But what is the responsibility of an action method? Well, an
action method receives a request and triggers appropriate logic to fetch data
from the data model and passes this data to views in order to show the
appropriate result to end users. So action methods are like the heart of the
controller class.
But how do action methods work? Action methods work based on
the parameters that are passed to them. Obviously, URL's represent the content
that a user is looking for and routing mechanism routes each request to the appropriate
controller class. But here, parameters specify the action that should take
place.
For instance, when the user is viewing a page like /Post?ID=5 then the request should be routed to PostController class where Post action method handles the
request in some ways.
Listing 2 adds an action method to Listing 1.
Listing 2
using System;
using System.Web;
using System.Web.Mvc;
namespace KBlog.Controllers
{
public class SampleController : Controller
{
[ControllerAction]
public void Index()
{
//Add action logic here
}
}
}
By default, there is a HomeController
class in ASP.NET MVC projects that handles requests to default home pages.
In the next section I will discuss more about the parameters
in action methods.