Handling Query Strings in MVC

In ASP.NET Core MVC, query strings are a simple yet powerful way to pass data from the browser to the server through the URL. They are widely used in real-world applications for filtering, searching, sorting, and pagination.

Whenever you see a URL with a ? (Question Mark) symbol followed by key-value pairs, you are looking at query string data being sent to the server.

Understanding how query strings work and how to handle them properly is essential for building dynamic and user-friendly web applications.


What Are Query Strings?

A query string is a part of a URL used to send data to the server in the form of key-value pairs.

It always starts with a ? symbol and contains one or more parameters separated by &.

Example:

/Product/Search?name=Laptop&price=50000

In this URL:

  • name = Laptop
  • price = 50000

Each parameter consists of a key and a value, where:

  • The key represents the variable name
  • The value represents the data being sent

Query strings are commonly used in:

  • Search functionality
  • Filtering data (price, category, rating)
  • Pagination (page=1, page=2)
  • Sorting (sort=asc, sort=desc)

They are easy to use and allow users to share URLs with specific data already applied.


Basic Example of Handling Query Strings

ASP.NET Core MVC automatically maps query string values to action method parameters using model binding.


public IActionResult Search(string name)
{
    return Content("Search for: " + name);
}

URL: /Product/Search?name=Laptop

Explanation:

  • The query string contains name=Laptop
  • The parameter name in the action method matches the query key
  • ASP.NET Core automatically assigns the value "Laptop" to the parameter

Output:

Search for: Laptop

This automatic mapping is one of the most powerful features of ASP.NET Core MVC.


Accessing Query String Values Manually in Controller

In ASP.NET Core MVC, query string values are usually mapped automatically to action method parameters using model binding. However, in some scenarios, you may need to access query string values manually.

This can be done using the Request.Query collection available inside the controller.


Reading Query String from URL


public IActionResult Search()
{
    var name = Request.Query["name"];
    
    return Content("Search for: " + name);
}

URL: /Product/Search?name=Laptop

Step-by-Step Explanation

  • Step 1: Request reaches the controller

    When the user enters the URL, the request is routed to the corresponding controller and action method.

  • Step 2: Access the Request object

    The Request object contains all details about the incoming HTTP request, including headers, body, and query string values.

  • Step 3: Use Request.Query collection

    Request.Query is a key-value collection that stores all query string parameters.

  • Step 4: Retrieve value using key

    Use the key (parameter name) to get the value:

    
    Request.Query["name"]
    

    This returns the value associated with the key name.

  • Step 5: Use the value in your logic

    The retrieved value can be used for filtering, searching, or processing data.


Handling Multiple Query Values

You can access multiple query string values in the same way:


var name = Request.Query["name"];
var price = Request.Query["price"];

URL: /Product/Search?name=Laptop&price=50000


Important Notes

  • Values are returned as strings – you may need to convert them to int, decimal, etc.
  • Check for null values to avoid runtime errors
  • This approach is useful when parameter names are dynamic or unknown at compile time

When Should You Use This Approach?

  • When parameter names are dynamic
  • When working with custom middleware or logging
  • When you need full control over request data

In most cases, automatic model binding is preferred, but understanding this manual approach gives you more control and flexibility.


Handling Multiple Query Parameters

You can pass multiple query parameters in a single URL and receive them in your action method.


public IActionResult Filter(string name, int price)
{
    return Content("Name: " + name + ", Price: " + price);
}

URL: /Product/Filter?name=Laptop&price=50000

Explanation:

  • The query string contains two parameters: name and price
  • ASP.NET Core matches both parameters with method arguments
  • The values are automatically converted to appropriate data types

This is commonly used in product filtering scenarios.


Using Default Values in Query Parameters

You can define default values for parameters in case the query string is not provided.


public IActionResult Search(string name = "All")
{
    return Content("Search: " + name);
}

Explanation:

  • If the URL does not include name, the default value "All" is used
  • This prevents null values and improves user experience

This is useful in search and filtering scenarios.


Using FromQuery Attribute

You can explicitly bind query string values using the [FromQuery] attribute.


public IActionResult Search([FromQuery] string name)
{
    return Content("Search: " + name);
}

Explanation:

  • This explicitly tells ASP.NET Core to read the value from the query string
  • Useful when multiple binding sources are involved

Binding Query Strings to a Model

For complex scenarios, query strings can be mapped to a model.


public class ProductFilter
{
    public string Name { get; set; }
    public int Price { get; set; }
}

public IActionResult Filter(ProductFilter filter)
{
    return Content("Name: " + filter.Name);
}

This approach makes code cleaner and easier to maintain.


Real-World Example: Search and Pagination

Query strings are heavily used in real-world applications.


public IActionResult Search(string keyword, int page = 1)
{
    return Content("Keyword: " + keyword + ", Page: " + page);
}

Explanation:

  • keyword is used for search
  • page is used for pagination
  • If page is not provided, default value is used

This pattern is used in search engines, e-commerce sites, and dashboards.


Understanding Model Binding for Query Strings

ASP.NET Core uses a feature called model binding to automatically map query string values to action method parameters.

This means:

  • No manual parsing of URL is required
  • Automatic conversion to correct data types
  • Cleaner and more readable code

Note: We will cover model binding in detail in upcoming lessons, including advanced scenarios such as binding from forms, routes, and request bodies.


Best Practices for Using Query Strings

  • Use meaningful and readable parameter names
  • Avoid passing sensitive data in query strings
  • Use models for complex data
  • Keep URLs clean and user-friendly

Common Mistakes to Avoid

  • Incorrect parameter names
  • Not handling null values
  • Passing too many parameters
  • Ignoring validation

Summary

Query strings are a powerful and flexible way to pass data in ASP.NET Core MVC applications.

They are widely used in search, filtering, and pagination scenarios.

By understanding how query strings work and how model binding handles them, you can build dynamic and efficient applications.