I am working on MVC3 project and I want to show a message when I use RedirectToAction in view. I have used ViewBag but it is not working.
Please anybody help me.
The TempData
controller property can be used to achieve this kind of functionality. It's disadvantage is that it uses the session storage in the background. This means that you'll have extra work getting it to function on a web farm, or that you need to turn on sessions in the first place.
Alternatively you could use cookies if you only need to transport a short message. Doing so does require you to properly secure the cookie in order to prevent tampering. MachineKey.Protect()
can help you do this.
I was facing the same problem you did and created a solution for it called FlashMessage. Perhaps this could save you some work. It's available on NuGet as well.
Using FlashMessage is easy. You simply queue a message before you call RedirectToAction()
as follows:
// User successfully logged in
FlashMessage.Confirmation("You have been logged in as: {0}", user.Name);
return RedirectToLocal(returnUrl);
In your view you include the following statement to render any previously queued messages:
@Html.RenderFlashMessages()