LearnFast.Ninja

MVC redirect to action with parameters

How to redirect form action to another and pass parameters to the new action. We will use the RedirectToAction function that redirects to the specified action using the action name as string and also we can pass variables as query string.

Main idea:
RedirectToAction("Step2"new { Name = William.FirstName });

Working example:


MyController.cs

namespace MyMVC.Controllers

{

    public class MyController : Controller

    {

        // GET: /My/

        public ActionResult Index()

        {

            User William = new User("William""Smith");

            return RedirectToAction("Step2"new { Name = William.FirstName });

        }

 

        public ActionResult Step2(string Name)

        {

            ViewData["Name"] = Name;

            return View();

        }

    }

}


Step2.cshtml
<h2>Hello @ViewData["Name"]</h2>

Result:


Tags

asp.net

mvc action redirecttoaction query-string