Parameters are the key part of the controller class and
specify the user's choice to actions methods. Parameters come directly from the
URL and its query parameters and you need to decide how to use them with your
own logic.
There are some different ways to handle parameters in action
methods and it is left to you to decide how to do this.
The first approach is to use query parameters and fetch them
in the action method from the URL. Obviously, this approach does not need any
parameter for the action method. Listing 3 shows such an action method that
retrieves the ID parameter from query string.
Listing 3
// Sample URL: /Page/Article?ID=5
[ControllerAction]
public void Article()
{
int id = Convert.ToInt32(Request["ID"]);
}
The first approach was something that you could do in all
ASP.NET web applications as well. In the second approach you pass the URL
parameter to the action method as its parameter by defining the type.
Listing 4 shows an example of this approach. You can simply
use the id parameter in your action method to write your logic.
Listing 4:
// Sample URL: /Page/Article?ID=5
[ControllerAction]
public void Article(int id)
{
// Implement the logic to handle the
// request based on the id parameter
}
The last way is similar to the previous one. You handle
parameters via action method parameters, but parameters also come from
sub-paths. So if you have a URL like /Page/Article/5, then 5 can be considered
as the ID parameter to be passed to the controller.
Listing 5 shows this in action.
Listing 5:
// Sample URL: /Page/Article/5
[ControllerAction]
public void Article(int id)
{
// Implement the logic to handle the
// request based on the id parameter
}
You can use nullable type arguments in order to pass
optional parameters to an action method. For instance, suppose that you have an
article that consists of several sections. In one case the user can request the
whole article and in an optional case he can also pass a Section parameter to
get a specific section based on its unique string title.
In listing 6 you see how this can be implemented.
Listing 6:
// Sample URL 1: /Page/Article/5
// Sample URL 2: /Page/Article/5?section=introduction
[ControllerAction]
public void Article(int id, string? section)
{
// Implement the logic to handle the request
// based on the id and/or section parameters
}