Sterling Duchess
Sterling Duchess

Reputation: 2100

Removing session variable in view

Why am I getting no output from this code if bellow it I add @{ 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>
            }

Does code first get evaluated and then outputted but even then it makes no sense. Without @{ Session.Remove("errors"); } I get the output with it nothing it's very annoying.

Trying to do FLASH messages that persist for only the current request.

Updated:

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

View:

        @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>
        }

Upvotes: 0

Views: 1115

Answers (1)

Nico
Nico

Reputation: 12683

Session State is meant to be persisted between requests, browser tabs and even after browser windows have been closed.

What you are probably looking for is TempData which is designed to do exactly as you wish.

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.

This works quite nicely for messages and alerts as you can redirect to another page (say invalid access reasons) and still persist this message until the next page is loaded.

Upvotes: 4

Related Questions