Skip to content
the poor coder

mvc return view with query string

Poor Man
Published
Reading time
1 min read
On this page

MVC Return View with Query String#

If you want to pass data from a controller to a view in an MVC application, you can use a query string. A query string is a set of parameters that are appended to the end of a URL.

Using RedirectToAction#

One way to pass data via query string from a controller to a view is to use the RedirectToAction method. This method redirects the user to a different action method within the same or another controller. Here's an example:

C#

public ActionResult Index()
{
    string name = "John";
    return RedirectToAction("Details", new {name = name});
}

public ActionResult Details(string name)
{
    ViewBag.Name = name;
    return View();
}

In this example, we're passing the value of "name" as a parameter in the RedirectToAction method. This value is then retrieved in the Details method via the "name" parameter.

Using View Data#

Another way to pass data via query string is to use ViewData. ViewData is a dictionary object that can be used to store data that will be passed between the controller and the view. Here's an example:

C#

public ActionResult Index()
{
    ViewData["Name"] = "John";
    return View();
}

In this example, we're setting the value of "Name" in the ViewData dictionary. This value can then be retrieved in the view using the following syntax:

HTML

@ViewData["Name"]

Using ViewBag#

Similar to ViewData, ViewBag is another way to pass data from a controller to a view. ViewBag is a dynamic object that can be used to store data that will be passed between the controller and the view. Here's an example:

C#

public ActionResult Index()
{
    ViewBag.Name = "John";
    return View();
}

In this example, we're setting the value of "Name" in the ViewBag object. This value can then be retrieved in the view using the following syntax:

HTML

@ViewBag.Name

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC