You have multiple options for passing multiple parameters to a GET method: FromRouteAttribute, FromQuery and Model Binding.
In this article, we are going to learn how to pass multiple parameters to a GET method. This article covers the following points:
FromRouteAttribute
FromQuery
There are more ways to pass multiple parameters to method, but following are the options mostly used for GET method:
FromRouteAttribute
FromQuery
FromRouteAttribute
In this option, the parameters are bound using the route data from current request.
Example:
FromQuery
In this option the parameters are bound using the request query string.
Example:
The model binding works with data coming from HTTP requests and passed to the controller and Razor pages as parameters. It works in the following ways:
It gets the data from various sources in the form of key-value pairs from the following sources:
To work with model binding, we need to use following attributes:
To work with complex types, the built-in attributes are available as follows:
For example, we are passing multiple parameters to GET method but in case our parameters exceed three, then it’s not readable and best practice to use that way. We can use class model as a parameter to a GET method with model binding as follows:
In the above example, you can see how we use model binding with GET action method and pass multiple parameters using query string, but model binding fetches data from it and binds to the model and passes that model to GET action method.
We can use both the options to pass multiple parameters to a GET method as follows:
In the above example, we pass one parameter using FromRouteAttribute
and two parameters using FromQuery
.
You can also download this example from here.
In this article, we discussed ways of passing multiple parameters to a GET method: FromRouteAttribute
, FromQuery
and Model Binding, using simple examples. If you have any suggestions or queries regarding this article, please contact me.
“Learn It, Share it.”
Jeetendra Gund is a C# Corner MVP as well as the Chapter Leader of C# Corner Pune Chapter. He holds a master’s degree in Computer Science and has worked on several different domains. He has spent six years in grooming his knowledge about Microsoft Technologies and has been sharing his experiences on technologies such as C#.Net, MVC.Net, SQL Server, Entity Framework, AngularJS, JavaScript, HTML, and .NET Static Code Analysis. He is a regular speaker at C# Corner on Microsoft Technologies. Find him: C# Corner, LinkedIn, or Twitter.