0

I want show the alert message when the user is added. It happens smoothly but when i press the back arrow of the browser from the another action it still shows the alert message.

//this is my partial view
<div class="row" id="alerts">
<div class="col-lg-12">
    @if (TempData["Success"] != null)
    {
        <div class="alert alert-success alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-
hidden="true">x</button>
            <h4><i class="icon fa fa-ban"></i> Alert!</h4>
            @TempData["Success"]
        </div>

    }
</div>
</div>

//this is my controller
 public ActionResult Add(CreateViewModel objCreate)
    {
        userRepo.AddUser( objCreate);

        TempData["Success"] = "User Added Successfully!";
        return RedirectToAction("Index");    
    }

//this is my view
<div class="col-md-10 col-md-offset-2">
            @Html.Partial("_Alerts")
            @RenderBody()
 </div>
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
Anand Shrestha
  • 39
  • 1
  • 11

2 Answers2

0

In your Index method, you can disable caching by using OutputCacheAttribute annotation like this

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
public ActionResult Index()
{
    // code of Index()

}
granit
  • 570
  • 4
  • 9
  • Thank you! it works fine but is it still the good way to do ? – Anand Shrestha Apr 06 '17 at 09:45
  • @AnandShrestha that will depend on your needs but the example above will disable caching for that particular action which is what is happening when you click somewhere after being redirected to Index then and click Back button on the browser. [Here](https://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.118).aspx) is the relevant documentation and [another relevant SO question](http://stackoverflow.com/questions/20895489/outputcache-setting-inside-my-asp-net-mvc-web-application-multiple-syntax-to-pr). Hope it helps. – granit Apr 06 '17 at 09:59
0

I think reason is when you go to back on the browser, it call controller and store value for TempData["Success"]

Try this using following code in your controller

public ActionResult Add(CreateViewModel objCreate)
{
   if (!IsPostBack){
      userRepo.AddUser( objCreate);
      TempData["Success"] = "User Added Successfully!";
   }
   return RedirectToAction("Index"); 
}
Thili77
  • 1,061
  • 12
  • 20