Oskar Groth Oskar Groth - 3 months ago 12
Javascript Question

display alert once per visit

I am working how to display alert message once if the user visits site first time. The message should be visible on every page until close button is pressed. I put the code in _Layout.cshtml, but it is not working I wonted to.

Can you point my mistake?

@if(Session["Alert"] != "Confirmed")
{
<div id="myAlert" class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong>Warning!</strong> Better check yourself, you're not looking too good.
</div>
}

<script type="text/javascript">
$(document).ready(function () {
$("#myAlert").on('closed.bs.alert', function () {
sessionStorage.Alert = "Confirmed";
});
});
</script>


The alert is displayed every time the site/page is reloaded. It looks as if the script is not executed when alert close button is pressed. What is more the session["Alert"] is not set.

Answer

sessionStorage and server side Session are not the same thing! You can't set values to sessionStorage and expect to get it from server side Session. So you have two choices:

1. Use server side Session

Change your javascript code to send an ajax request to a mvc action, then set Session["Alert"] to "Confirmed" there.

2. Use sessionStorage

Instead of using @if(Session["Alert"] != "Confirmed"), you check sessionStorage on document ready to decide whether to show the alert.

The 2nd one requires minimum code to change. The following code will work :

<div id="myAlert" style="display:none" class="alert alert-warning alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <strong>Warning!</strong> Better check yourself, you're not looking too good.
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $(document).ready(function () {
            // If not 'Confirmed', show #myAlert
            if (sessionStorage.Alert !== 'Confirmed') {
                $('#myAlert').show();
            }
        });

        $('#myAlert .close').click(function () {
            // Set 'Alert' to 'Confirmed' when user click the close button
            sessionStorage.Alert = "Confirmed";
            $(this).closest('#myAlert').hide();
        });
    });
</script>