Set Viewbag before Redirect

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

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


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

Tags:

C#

Asp.Net Mvc