powered by Slim Framework
enhanced by Nesbot.com

MVC 3: Pass Model or Form Data through a Redirect

Published on Feb 6, 2012 by Jamie Munro

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.

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:


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));
}
}
}


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:


using MvcContrib.Filters;

[PassParametersDuringRedirect]


The first one is a basic using statement 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.

Summary


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!

Tags: ASP.NET | mvc3

<- jQuery: Padding a Variable or String with a Specific Character  Home JavaScript: Set Cursor Position of textarea -> 
blog comments powered by Disqus