Set Viewbag before Redirect
Is it possible to set the ViewBag
before I call a redirection?
I want something like:
@ViewBag.Message="MyMessage";
RedirectToAction("MyAction");
Solution 1:
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();
}
Solution 2:
You can use the TempData in this situation. Here is some explanation for the ViewBag, ViewData and TempData.
Solution 3:
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);
}
Solution 4:
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.