在视图中删除会话变量

Removing session variable in view

如果在下面添加 @{ Session.Remove("errors"); }

,为什么我没有从这段代码中得到任何输出
            @if (Session["errors"] != null)
            {

                <div class="alert alert-danger">
                    <ul>
                        @{
                            String[] errors = (String[])Session["errors"];
                        }
                        @foreach (String error in errors)
                        {
                            <li>@error</li>
                        }
                    </ul>
                </div>
            }

            @if (Session["success"] != null)
            {
                <div class="alert alert-success">
                    @Session["success"]
                </div>
            }

代码是否先被评估然后输出,但即使这样也没有任何意义。没有 @{ Session.Remove("errors"); } 我得到的输出什么也没有,这很烦人。

正在尝试执行仅针对当前请求持续存在的 FLASH 消息。

更新:

        TempData["errors"] = new String[] { "You need to be logged in to access this page." };

查看:

        @if (TempData.ContainsKey("errors"))
        {

            <div class="alert alert-danger">
                <ul>
                    @{
                        String[] errors = (String[])TempData["errors"];
                    }
                    @foreach (String error in errors)
                    {
                        <li>@error</li>
                    }
                </ul>
            </div>
        }

        @if (TempData.ContainsKey("success"))
        {
            <div class="alert alert-success">
                @TempData["success"]
            </div>
        }

会话状态旨在在请求、浏览器选项卡之间甚至在浏览器 windows 关闭后持续存在。

您可能正在寻找的是 TempData,它的设计完全符合您的要求。

The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.

这对于消息和警报非常有效,因为您可以重定向到另一个页面(比如无效的访问原因)并且在加载下一页之前仍然保留此消息。