3

Imagine I have one controller that register somebody and if successful should display a message on another controller view.

   [HttpPost]
   public ActionResult Register(RegisterModel model)
   {
       string msg = db.Register(model) 

       // Assuming msg contains "You have been succesfully registered" 
       // How do I display that on the Dashboard view??

       return RedirectToAction("Index", "Dashboard");
   }

What's the best way to pass a message or a series of messages to the Dashboard controller??
Even better if I can pass a list of objects with their own properties (something like obj.Status && obj.Message)

SF Developer
  • 5,244
  • 14
  • 60
  • 106

2 Answers2

2

You could use the TempData property. This will keep the data for 1 request so you will be able to access this on a Redirect.

TempData["MyObject"] = new MyObj
{
    prop1 = "Test",
    prop2 = "Prop"
}

You can then access it like:

var myObj = TempData["MyObject"] as MyObj;

OR

var myObj = (MyObj)TempData["MyObject"];

You can also make an extension method:

public MyObj GetMyObj(this TempDataDictionary tmpData)
{
    return (MyObj)tmpData["MyObject"];
}

Then access it this way:

var myObj = TempData.GetMyObj();
Community
  • 1
  • 1
DSlagle
  • 1,563
  • 12
  • 19
1

They recomend to use TempData dictionary for this purpose.

[HttpPost]
public ActionResult Register(RegisterModel model)
{
   string msg = db.Register(model) 

   TempData["Message"] = "You are registered!";

   return RedirectToAction("Index", "Dashboard");
}

TempData can be used as ViewData, but internaly it lives in Session, and MVC itself takes care about cleaning it up after single redirect.

Only thing is - if you use web farm (more than one web server), you will need to configure your sessions properly to use the same storage (usually database)

There are also discussion in this question

Community
  • 1
  • 1
Andrey Kuleshov
  • 645
  • 6
  • 19