I am confused by passing data from one ActionResult
to another ActionResult
method.
What this is about let me describe,
I need to pass value from one method to another, and that value must be available on view that I'm rendering from that another method.
What I saw in my project is this (this is Edit but [HttpPost
] Edit, and it is redirecting to Edit also but with [HttpGet
] insted of [HttpPost
]):
TempData["Success"] = True;
return RedirectToAction("Edit/" + customer.Id, "Customer");
And what is done on [HttpGet] Edit :
if (TempData["Success"] != null && TempData.ContainsKey("Success"))
ViewBag.Success = Convert.ToString(TempData["Success"]);
return View(model);
As you can see guys on [HttpPost
] TempData["Success"]
is set to True
;
And Redirection is made to [HttpGet
] method and there is written next code:
if (TempData["Success"] != null && TempData.ContainsKey("Success"))
ViewBag.Success = Convert.ToString(TempData["Success"]);
return View(model);
So I am wondering why it's needed to set TempData
and later based on value of that TempDate
let's set value to a ViewBag
, can't I just set value of ViewBag on my first ActionResult before redirection so it can be available also on a View even if view is being rendered/called from HttpGet
action result?
For example:
instead of this:
TempData["Success"] = True;
return RedirectToAction("Edit/" + customer.Id, "Customer");
Can I simply write in my HttpPost
ViewBag.Success = True;
return RedirectToAction("Edit/" + customer.Id, "Customer");
Or this is needed to be done with TempData
because ViewBag
wouldn't be available on a View if I don't put value in it on a ActionResult which is redirecting to a View, and in this case it is HttpGet and not HttpPost (so that means I need to set ViewBag value on a HttpGet?)
And If I must do it this way, I could also use two ViewBags, and not ViewBag and TempData?
And why would someone solve it like this at all? Is this correct approach or what?