2017-04-06 32 views
0

我想在添加用戶時顯示警報消息。它會順利發生,但是當我從另一個動作中按下瀏覽器的後退箭頭時,它仍然顯示警報消息。當我點擊另一個動作的箭頭時Tempdata沒有被清除?

//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> 

回答

0

索引中的方法,你可以通過使用OutputCacheAttribute註釋這樣

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

} 
+0

謝謝!它工作正常,但它仍然是一個好方法嗎? –

+0

@AnandShrestha將取決於您的需求,但上面的示例將禁用該特定操作的緩存,這是您在重定向到索引後單擊某處並在瀏覽器上單擊「返回」按鈕時發生的情況。 [Here](https://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v = vs.118).aspx)是相關的文檔和[另一個相關的SO問題](http ://stackoverflow.com/questions/20895489/outputcache-setting-inside-my-asp-net-mvc-web-application-multiple-syntax-to-pr)。希望能幫助到你。 – granit

0

禁用緩存我想原因是當你去回瀏覽器,它呼叫控制器和存儲值TempData["Success"]

在你的控制器試試這個使用下面的代碼

public ActionResult Add(CreateViewModel objCreate) 
{ 
    if (!IsPostBack){ 
     userRepo.AddUser(objCreate); 
     TempData["Success"] = "User Added Successfully!"; 
    } 
    return RedirectToAction("Index"); 
} 
+0

它給出錯誤「名稱'IsPostBack'在當前上下文中不存在」 –

+0

添加引用檢查此 - https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback (v = vs.110)的.aspx – Thili77

相關問題