138

Is it possible to set the ViewBag before I call a redirection?

I want something like:

@ViewBag.Message="MyMessage";
RedirectToAction("MyAction");
SharpC
  • 6,974
  • 4
  • 45
  • 40
daniel
  • 34,281
  • 39
  • 104
  • 158

5 Answers5

278

When you use redirection, you shall not use ViewBag, but TempData

public ActionResult Action1 () {
 TempData["shortMessage"] = "MyMessage";
 return RedirectToAction("Action2");
}

public ActionResult Action2 () {
 //now I can populate my ViewBag (if I want to) with the TempData["shortMessage"] content
  ViewBag.Message = TempData["shortMessage"].ToString();
  return View();
}
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • 1
    Why do you have @ViewBag if you're not in the view? – apkisbossin Dec 02 '15 at 21:20
  • 9
    I would like to complete the answer because I am using it and I faced a small problem that is when the TempData is empty for some reason (in my case I only have a message when a conversion is made). So I had to had the test if(TempData["Message"] != null) to avoid an error. – Patrick Aug 19 '16 at 09:33
  • 2
    What if the redirection is to other controller? In the other controller's action ViewBag, TempData and Session are all empty! – Andrew Jun 09 '17 at 20:04
  • 2
    @Andrew well, TempData is not related to a specific controller. Maybe you do more than one redirection, and lose TempData ? You may link to a new question with some code... – Raphaël Althaus Jun 11 '17 at 08:16
  • I was trying to set those in the OnAuthorize metiod of a filter attribute, but none worked, so I ended up using the query string to pass the data. The other way around, setting TempData in the controller worked when I later needed to read that in the filter attribute. Thanks! – Andrew Jun 11 '17 at 17:25
  • However, to access TempData in a filter attribute you have to do `filterContext.Controller.TempData`, so it looks like it's related to the controller (I didn't test to check if it's shared with others). – Andrew Jun 11 '17 at 17:35
  • 1
    @RaphaëlAlthaus adjust your answer to `TempData["shortMessage"]?.ToString() to avoid a potential null reference – Aaron Hudon Jun 01 '18 at 03:02
  • FOR those of you that are still getting empty, do not use the return RedirectToAction(nameOf(YourAction)). For some reason it empties TempDate. Simply using the string fixed my issue. – Stanley Backlund Feb 02 '22 at 21:50
16

You can use the TempData in this situation. Here is some explanation for the ViewBag, ViewData and TempData.

laszlokiss88
  • 4,001
  • 3
  • 20
  • 26
  • Thanks. This helped. I did not want to redesign my form submission, but I was redirecting to the same page after submit to allow a new record to be created - but I needed to pass something. TempData was the way to go - because I cannot redirect to a controller action with a Model. But I can pass TempData. That works great! I didnt have to rewrite my form submission. – John Foll Jun 22 '23 at 17:18
14

I did like this..and its working for me... here I'm changing password and on success I want to set success message to viewbag to display on view..

    public ActionResult ChangePass()
    {
        ChangePassword CP = new ChangePassword();
        if (TempData["status"] != null)
        {
            ViewBag.Status = "Success";
            TempData.Remove("status");
        }
        return View(CP);
    }

    [HttpPost]
    public ActionResult ChangePass(ChangePassword obj)
    {
        if (ModelState.IsValid)
        {
            int pid = Session.GetDataFromSession<int>("ssnPersonnelID");
            PersonnelMaster PM = db.PersonnelMasters.SingleOrDefault(x => x.PersonnelID == pid);

            PM.Password = obj.NewPassword;
            PM.Mdate = DateTime.Now;
            db.SaveChanges();

            TempData["status"] = "Success";
            return RedirectToAction("ChangePass");
        }

        return View(obj);
    }
RAVI VAGHELA
  • 877
  • 1
  • 10
  • 12
3

Taken from here

Summary

The ViewData and ViewBag objects give you ways to access those extra pieces of data that go alongside your model, however for more complex data, you can move up to the ViewModel. TempData, on the other hand, is geared specifically for working with data on HTTP redirects, so remember to be cautious when using TempData.

Community
  • 1
  • 1
Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
-3

Or you can use Session for alternative:

Session["message"] = "MyMessage";
RedirectToAction("MyAction");

and then call it whenever you need.

UPDATE

Also, as what @James said in his comment, it would be safe to nullify or clear the value of that specific session after you use it in order to avoid unwanted junk data or outdated value.

Jon P
  • 826
  • 1
  • 7
  • 20
  • 4
    I don't agree on that. don't use session for this. – Mahmood Dehghan Apr 27 '14 at 11:41
  • 2
    It IS an alternative. It is preferable in certain situations. – csharpforevermore Jun 07 '15 at 22:48
  • Session variables are useful for things that you need to keep track of between several posts/gets. For a one-off use like this, you HAVE to remember to clear it, or it'll be junk data later on, appearing unwanted on some screen, or even triggering logic out of context. – James Sep 15 '15 at 20:49
  • @James Exactly, that's what I do for some cases I need to use this approach. Nullifying or clearing its value after use is a must for cases like these. – Jon P Sep 16 '15 at 00:38