Back to: ASP.NET Core Tutorials For Beginners and Professionals
Model Binding using FromQuery in ASP.NET Core MVC
I will discuss How to Use FromQuery to Perform Model Binding in ASP.NET Core MVC with Examples in this article. Please read our previous article discussing Model Binding using FromForm in ASP.NET Core MVC.
Model Binding using FromQuery in ASP.NET Core MVC
In ASP.NET Core MVC, the FromQuery attribute indicates that a parameter should be bound using data from the query string of the HTTP request. The query string is the part of a URL after the “?” Character, composed of key-value pairs separated by & characters.
The FromQuery attribute is especially useful for scenarios like filtering, where you want to fetch data based on certain criteria passed through the URL. If you go to the definition of FromQueryAttribute, you will see the following signature.
The FromQueryAttribute specifies that a parameter or property should be bound using the request query string.
Example to Understand FromQueryAttribute in ASP.NET Core MVC:
Suppose we have a scenario where we are searching for users based on a name or an age. So, let us first create a model to hold the search string. Create a class file named UserSearchCriteria.cs and copy and paste the following code.
namespace ModelBindingDemo.Models { public class UserSearchCriteria { public string Name { get; set; } public int Age { get; set; } } }
Next, create another class file with the name User.cs within the Models folder and then copy and paste the following code into it. This is a simple model that represents a user.
namespace ModelBindingDemo.Models { public class User { public int Id { get; set; } public string? Name { get; set; } public int Age { get; set; } public string? Mobile { get; set; } } }
Next, create a controller named UsersController and copy and paste the following code into it. In the following example, we are binding query parameters to a model, but you can also bind them directly to action method parameters.
using Microsoft.AspNetCore.Mvc; using ModelBindingDemo.Models; namespace ModelBindingDemo.Controllers { public class UsersController : Controller { private List<User> _users; public UsersController() { _users = new List<User>() { new User(){Id =1, Name ="Pranaya", Age = 35}, new User(){Id =2, Name ="Priyanka", Age = 30}, new User(){Id =3, Name ="Anurag", Age = 35}, new User(){Id =4, Name ="Prateek", Age=30}, new User(){Id =5, Name ="Hina", Age=35} }; } [HttpGet("users/search")] public IActionResult Search([FromQuery] UserSearchCriteria criteria) { List<User> FilteredUsers = new List<User>(); if (criteria != null) { if (!string.IsNullOrEmpty(criteria.Name) && criteria.Age > 0) { FilteredUsers = _users.Where(x => x.Name.ToLower().StartsWith(criteria.Name.ToLower()) || x.Age > criteria.Age).ToList(); } else if(!string.IsNullOrEmpty(criteria.Name)) { FilteredUsers = _users.Where(x => x.Name.ToLower().StartsWith(criteria.Name.ToLower())).ToList(); } else if (criteria.Age > 0) { FilteredUsers = _users.Where(x => x.Age > criteria.Age).ToList(); } } return Ok(FilteredUsers); } } }
Query URLs:
When calling the above endpoint, you can provide search criteria through the query string as follows:
- /users/search?Name=pr
- /users/search?Age=30
- /users/search?Name=Pr&Age=30
In the above scenarios, the values from the query string (Name and Age) will be bound to the properties of the UserSearchCriteria object. This is possible because of the FromQuery attribute.
If you bind directly to method parameters rather than a model, you can still use the FromQuery attribute. For a better understanding, please modify the UsersController as follows:
using Microsoft.AspNetCore.Mvc; using ModelBindingDemo.Models; namespace ModelBindingDemo.Controllers { public class UsersController : Controller { private List<User> _users; public UsersController() { _users = new List<User>() { new User(){Id =1, Name ="Pranaya", Age = 35}, new User(){Id =2, Name ="Priyanka", Age = 30}, new User(){Id =3, Name ="Anurag", Age = 35}, new User(){Id =4, Name ="Prateek", Age=30}, new User(){Id =5, Name ="Hina", Age=35} }; } [HttpGet("users/search")] public IActionResult Search([FromQuery] string Name, [FromQuery] int? Age) { List<User> FilteredUsers = new List<User>(); if (!string.IsNullOrEmpty(Name) && Age != null && Age > 0) { FilteredUsers = _users.Where(x => x.Name.ToLower().StartsWith(Name.ToLower()) || x.Age > criteria.Age).ToList(); } else if (!string.IsNullOrEmpty(Name)) { FilteredUsers = _users.Where(x => x.Name.ToLower().StartsWith(Name.ToLower())).ToList(); } else if (Age != null & Age > 0) { FilteredUsers = _users.Where(x => x.Age > Age).ToList(); } return Ok(FilteredUsers); } } }
If the parameter names and query string keys match, you don’t strictly need the FromQuery attribute for binding to work. However, using the attribute explicitly clarifies your intention and makes the code more maintainable and understandable. Ensure to handle potential null values or provide default values if some query parameters are optional. In the example above, int? Age means age can be null.
When to use FromQuery Attribute in ASP.NET Core MVC?
Here are scenarios where you would typically use the FromQuery attribute:
Filtering and Sorting in List Views:
In APIs or web pages that display lists of items (like a product list or user list), query parameters are commonly used for filtering, sorting, or specifying which fields to display.
/products?category=electronics&sort=price-asc /users?ageGreaterThan=20&ageLessThan=50&orderBy=name
Pagination:
For endpoints that support pagination, query parameters are often used to specify the current page, page size, or offset.
/articles?page=3&pageSize=20
Searching:
For search functionality, query parameters might take search terms, filters, and other related options.
/search?query=asp.net+core
Stateful Navigation:
In traditional web applications, query parameters can be used to maintain certain states when navigating between pages, like selected tabs, grid column order, expanded sections, and more.
Feature Flags or Toggles:
Sometimes, apps might have experimental features that can be toggled on or off using query parameters.
/dashboard?experimentalFeature=true
Configuration or Personalization:
Using the query string is a common approach if an endpoint can be personalized or configured based on parameters.
/report?theme=dark&fontSize=large
Redirects with Information:
Sometimes, after completing an action, a user might be redirected to another page, and you want to pass some information or a message. Query parameters can be a way to do this without changing the path.
/login?returnUrl=/dashboard
Analytics or Tracking:
If you’re integrating with analytics or tracking tools, often, they attach additional query parameters to URLs to track campaigns, referrals, and more.
Advantages of Using Query Parameters:
- Stateless Nature: APIs that rely on query parameters can remain stateless, which is advantageous for scalability and maintainability.
- Easy to Test: It’s easy to test endpoints with different parameters by just changing the URL.
- Bookmarkable and Shareable: Users can bookmark URLs with specific parameters or share them with others.
When Not to Use:
- Sensitive Data: Never pass sensitive data in the query string, like passwords or security tokens. They can be logged in server logs, browser history, or referrer headers, posing a security risk.
- Very Large Data Sets: Browsers and servers have length limits for URLs. If there’s a risk of the query string becoming too long, it’s better to use a different method, like sending a JSON payload in the POST request body.
Remember, while the FromQuery attribute is useful for capturing individual query parameters, if you want to bind multiple query parameters to a single model, you can use the FromQuery attribute on a complex parameter, and ASP.NET Core will handle binding the individual properties of that model to the corresponding query parameters.
In the next article, I will discuss How to Use FromRoute to perform Model Binding in ASP.NET Core MVC with Examples. In this article, I explain How to use FromQuery to Perform Model Binding in ASP.NET Core MVC with Examples. I hope you enjoy this FromQuery in ASP.NET Core MVC article.