I have following ActionResult
in a controller
and you can see that I set a message in the ViewBag
if it\'s successful. Then on the
The viewbag/viewdata scope is available for controller to view only. if you use tempdata, it will available one request , you can extend more than one request
The ViewBag property enables you to dynamically share values from the controller to the view. (MSDN)
It’s life lies only during the current request, and if redirection occurs then it’s value becomes null.
And since you using RedirectToAction
, which redirects to some different controller, value of ViewBag
is lost.
Consider using TempData
instead.
TempData["ResultMessage"] = "Role created successfully.";
(See this for usage)
ViewBag
helps to maintain data when you move from controller
to view
. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers
and views
. It’s a communication mechanism within the server call.
Since you are using RedirectToAction
, the ViewBag
becomes null
when it reaches the view
.
you can use TempData
for this:
TempData["ResultMessage"] = "Role created successfully.";
It uses Session
as storage, but it will not be around after the second response.
TempData
helps to maintain data when you move from one controller
to other controller
or from one action to other action. In other words, when you redirect, Tempdata
helps to maintain data between those redirects. It internally uses session variables. TempData
use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view.
For more understanding on this refer this link