How to show success message in view when RedirectToAction used

前端 未结 2 1506
鱼传尺愫
鱼传尺愫 2021-01-31 10:26

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.

相关标签:
2条回答
  • 2021-01-31 11:01

    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");
    
    0 讨论(0)
  • 2021-01-31 11:23

    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()
    
    0 讨论(0)
提交回复
热议问题