Use querystring variables in Asp .Net MVC controller

In an ASP.NET MVC application, you can use query string variables to pass data from the client (usually through the URL) to your controller actions. Query string variables are the key-value pairs appended to the end of a URL after a question mark (?). In MVC, you can easily access and use these query string parameters in your controller actions. Here's how you can do it with code examples:

Let's say you have a URL like this: http://example.com/MyController/MyAction?id=123&name=John

You want to retrieve the id and name values from the query string in your controller action.

  1. Create an MVC Controller:

First, create an MVC controller. In this example, let's call it MyController.

using System;
using System.Web.Mvc;

public class MyController : Controller
{
    public ActionResult MyAction()
    {
        // Your code to handle the query string variables goes here

        return View();
    }
}
  1. Access Query String Variables in the Controller Action:

You can access the query string variables using the Request.QueryString collection. Here's how you can retrieve the id and name variables from the URL:

public ActionResult MyAction()
{
    // Get the "id" and "name" query string variables
    string id = Request.QueryString["id"];
    string name = Request.QueryString["name"];

    // Use the values in your action
    // For example, you can pass them to the view or perform some logic
    ViewBag.Id = id;
    ViewBag.Name = name;

    return View();
}
  1. Use the Query String Variables in a View:

You can then use the ViewBag or a model to display the query string values in your view.

<!-- MyAction.cshtml -->
<h1>Query String Variables</h1>
<p>ID: @ViewBag.Id</p>
<p>Name: @ViewBag.Name</p>

Now, when you access the URL http://example.com/MyController/MyAction?id=123&name=John, the id and name query string variables will be passed to the MyAction action, and their values will be displayed in the view.

Keep in mind that query string variables are not the only way to pass data to a controller action in MVC. You can also use route parameters, form data, or other methods depending on your application's requirements.

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
2 + 6 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice