Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show success message in view when RedirectToAction used

Tags:

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.

like image 468
Mukesh Kumar Avatar asked Jan 11 '15 10:01

Mukesh Kumar


2 Answers

you can use TempData to show the message

in your View

@if (TempData["Success"] != null)
{
 <p class="alert alert-success" id="successMessage">@TempData["Success"]</p>
}

and in your controller after success

TempData["Success"] = "Added Successfully!";
return RedirectToAction("actionname", "controllername");
like image 174
Ritesh Kumar Avatar answered Sep 18 '22 16:09

Ritesh Kumar


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()
like image 36
Christ A Avatar answered Sep 22 '22 16:09

Christ A