How to run an Alert only once in an Asp.net MVC View

Asked

Viewed 230 times

1

I have a project in Asp.net mvc and in my view has an Alert that runs whenever the page is loaded (it closes automatically). The problem is that every time I make a Submit and the view is reloaded, the Alert appears. I need it to be opened only when the page is first accessed. Is there any way to do this with JS and preferably without using cookies?

HTML

<div id="alert-dicas" role="alert" class="alert alert-warning alert-icon alert-dismissible">
    <button id="btn-close-dicas" aria-label="Close" class="close" type="button">
        <span aria-hidden="true">×</span>
    </button>
    <i class="icon fa-lightbulb-o" aria-hidden="true"></i>
    <h4>Dica</h4>
    <p>
        mensagem aqui...
    </p>
</div>

Javascript

$(document).ready(function (e) {

    $("#alert-dicas").fadeTo(15000, 500).slideUp(500, function () {
        $("#alert-dicas").slideUp(500);
    });

    $('#frmBackupRestore').on('submit', function (e) {
        //e.preventDefault();

        if (checkFormValidateOrNotBackupRestore() == true) {
            startLoadOneMoment();
        }
    });

});
  • without using cookies? only if you save the information on the server, in a database, to know that it has already been displayed

  • Um, I can’t think of anything that doesn’t need to save the request status. Ever thought about using localStorage?

  • Another option is to do as @Ricardopunctual commented.

  • you will need to use a repository to save, cookies, as @Geiltonxavier commented localstorage, a database... if you do not need to be really a single time, you can use a Sessioner, at least during the session it will not appear again, only when the browser closes or the session expires

  • I think using the tb database would not be very viable for my case... How to do this using Sesssion?

1 answer

1

1st Method - Session

You can make this check using Session through codes Razor on your page, adding a simple condition:

@if (Session["MostrouAlerta"] == null)
{
  Session["MostrouAlerta"] = true;
  {...}
}

But this way every time you miss the session it will enter the condition again.

2nd Method - Cookies

To make through cookies so that it no longer displays or after losing the session do as follows:

Add to your javascript which shows/hides the alert code to store the value in the cookie:

document.cookie = "mostrouAlerta=true";

Then make the same condition to print the code on your page using Razor:

if (Request.Cookies["mostrouAlerta"].Value== "true")
{
  {...}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.