Have you ever wanted to pass form data or perhaps even a full model from one action to another through a RedirectToAction? By adding a new library package from NuGet, this can be accomplished with a few small changes to your controllers.
The first thing that needs to be done is to install the package through the NuGet package manager. Inside of Visual Studio, with the your MVC project selected select Tools -> Library Package Manager -> Add Library Package Reference… On the left hand side, select the Online button. Then, in the search field, type MvcContrib and install the base package and you can explore how to truncate string with C#.
Using MvcContrib with RedirectToAction
For simplicities sake, I am going to create a new controller called TestController. It will contain two functions, an index and a form function. The Form function will accept a model from a form post. Inside of this function, a new model is instantiated and populated with data, this data is then passed to the Index function via a RedirectToAction call.
Below is the full source code of this controller:
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcContrib.Filters;
namespace MvcApplication4.Controllers
{
[PassParametersDuringRedirect]
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index(TestIndexModel model)
{
return View(model);
}
[HttpPost]
public ActionResult Form(TestFormModel model)
{
TestIndexModel indexModel = new TestIndexModel();
indexModel.aVariable = “Put content here”;
return this.RedirectToAction(m => m.Index(indexModel));
}
}
}
[/code]
Most of the above code should look pretty similar to how MVC passes variables inside of functions or to views. The two key pieces of code that allow this behavior to function are these two lines:
[code]
using MvcContrib.Filters;
[PassParametersDuringRedirect]
[/code]
The first one is a basic using statement which is quite similar to how I leverage CASE Statement in SQL to include a reference to MvcContrib. The second line is placed above the controller definition telling MVC to do exactly what the meta data is called: Pass Parameters During Redirect.
By including a NuGet package called MvcContrib you can easily pass model or form data through a simple RedirectToAction function call inside of your controllers. The data will then be handled in the other view and be strongly typed to the model you are passing through the redirect. This is an excellent way to pass multi-step form data in a clean and readable fashion!