【问题标题】:Tempdata not being cleared when i click back arrow from another action?当我单击另一个操作的后退箭头时,临时数据没有被清除?
【发布时间】:2017-09-01 02:48:19
【问题描述】:

我想在添加用户时显示警报消息。它发生得很顺利,但是当我从另一个操作中按下浏览器的后退箭头时,它仍然显示警报消息。

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

【问题讨论】:

    标签: javascript c# asp.net asp.net-mvc tempdata


    【解决方案1】:

    在您的 Index 方法中,您可以像这样使用 OutputCacheAttribute 注释来禁用缓存

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

    【讨论】:

    • 谢谢!它工作正常,但它仍然是好方法吗?
    • @AnandShrestha 这将取决于您的需要,但上面的示例将禁用该特定操作的缓存,当您在被重定向到索引后单击某处然后单击浏览器上的“后退”按钮时会发生这种情况。 Here 是相关文档,another relevant SO question。希望对您有所帮助。
    【解决方案2】:

    我认为原因是当您返回浏览器时,它会调用控制器并为 TempData["Success"] 存储值

    在您的控制器中使用以下代码尝试此操作

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    相关资源
    最近更新 更多