5. Understand Parameters in Controller

Modify the code to pass some parameter information from the URL to the controller. For example, /HelloWorld/Welcome?name=Rick&numtimes=4.

Step 1: Change the Welcome method to include two parameters as shown in the following code.

HelloWorldController.cs
// GET: /HelloWorld/Welcome/ 
// Requires using System.Text.Encodings.Web;
public string Welcome(string name, int numTimes = 1)
{
    return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is: {numTimes}");
}

Step 2: Run the app and browse to: https://localhost:5001/HelloWorld/Welcome?name=Rick&numtimes=4.

Try different values for name and numtimes in the URL. The MVC model bindingarrow-up-right system automatically maps the named parameters from the query string to parameters in the method. See Model Bindingarrow-up-right for more information.

Browser window showing an application response of Hello Rick, NumTimes is: 4

Last updated