Extracting Parameters from URL in .NET MVC

In ASP.NET MVC, extracting parameters from URLs is a common requirement. Whether you need to retrieve query parameters or route values, the framework offers straightforward methods to achieve this. In this blog post, we'll explore how to extract parameters from URLs in both the View and Controller, providing practical code examples for each.

Sample URL

Here is the sample URL we will use:

https://example.com/search?q=laptop&page=3

Extracting Parameters in the View

In the View, you might want to display specific data based on the URL parameters. Here's an example of how to extract query parameters using Razor syntax:

@{
    string searchTerm = Request.QueryString["q"];
    int pageNumber = int.Parse(Request.QueryString["page"] ?? "1");
}

In this example, we're extracting the "q" (search term) and "page" (page number) query parameters from the URL. The Request.QueryString collection allows us to access these parameters easily.

Extracting Parameters in the Controller

In the Controller, you can extract parameters from the URL using route values or query parameters, depending on how your routes are configured. Let's see how to do this:

Using Route Values

Assuming you have a route defined in your RouteConfig.cs like this:

routes.MapRoute(
    name: "BlogPost",
    url: "blog/{year}/{month}/{slug}",
    defaults: new { controller = "Blog", action = "Post" }
);

You can extract the parameters in the corresponding controller action:

public ActionResult Post(int year, int month, string slug)
{
    // Your logic to retrieve and display the blog post
    // Example: return View(year, month, slug);
}

The values year, month, and slug will be automatically mapped from the URL to the corresponding action parameters.

Using Query Parameters

If your URL contains query parameters instead, you can extract them in the Controller action like this:

public ActionResult Search(string q, int page = 1)
{
    // Your logic to search and display results based on 'q' and 'page'
    // Example: return View(q, page);
}

Here, the q and page parameters will be automatically bound to the query parameters in the URL.

Or Like this:

public ActionResult Search()
{
string searchTerm = Request.QueryString["q"];                
int pageNumber = int.Parse(Request.QueryString["page"] ?? "1"); 
// Your logic to search and display results based on 'q' and 'page'
}
 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice