mvc return view with query string
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:
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:
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:
@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:
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:
@ViewBag.Name