What is the best way to display a pop-up notification once a user has successfully logged in?

I'm currently developing a website using asp.net core mvc for an assignment. The website features identity server for user authentication. I am attempting to display a pop-up alert once a user enters the correct login credentials and clicks the Login button (similar to a JavaScript alert). To achieve this, I have created a boolean property in the .cs file that is set to true when a user successfully logs in. In the .cshtml file, I have included a script block containing a function that triggers an alert when the boolean property is true. However, the problem I'm facing is that the function executes when the page is loaded (at which point the property is still false), even though I have configured it to fire only on button click. Any suggestions on what might be causing this issue?

Login.cshtml
@page
@model LoginModel

@{
    ViewData["Title"] = "Log in";
}

<div class="container w-50 text-center">
    <h1 class="display-4" style="margin-bottom: 80px;">@ViewData["Title"]</h1>
    <section>
        <form id="account" method="post">
            <h4>Use a local account to log in.</h4>
            <hr />
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Input.Email"></label>
                <input asp-for="Input.Email" class="form-control" />
                <span asp-validation-for="Input.Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.Password"></label>
                <input asp-for="Input.Password" class="form-control" />
                <span asp-validation-for="Input.Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <div class="checkbox">
                    <label asp-for="Input.RememberMe">
                        <input asp-for="Input.RememberMe" />
                        @Html.DisplayNameFor(m => m.Input.RememberMe)
                    </label>
                </div>
            </div>
            <div class="form-group">
                <button onclick="showAlert()" type="submit" class="btn btn-primary">Log in</button>
            </div>
            <div class="form-group">
                <p>
                    <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
                </p>
            </div>
        </form>
    </section>
</div>
<script type="text/javascript">
    showAlert = function () {
        if (@LoginModel.alert) {
            alert("Logged in succesfully");
            @LoginModel.alert = false;
        }
    }
</script>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

Login.cshtml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using BookingApp.ApplicationLogic.DataModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace BookingApp.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {
        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;
        private readonly ILogger<LoginModel> _logger;
        [BindProperty] static public bool alert { get; set; } = false;

        public LoginModel(SignInManager<User> signInManager,
            ILogger<LoginModel> logger,
            UserManager<User> userManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string ErrorMessage { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl = returnUrl ?? Url.Content("~/");

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    alert = true;
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}

Answer №1

Can we really rely on @LoginModel.alert to return a JavaScript boolean value? My experience suggests otherwise when mixing JS and razor.

If the data extracted is not clearly recognized as a boolean by JavaScript, it falls under the category of "truthy". For instance, if it's interpreted as a string, JS will evaluate it as "true".

In my opinion, it's always best practice to use strict comparison === in JavaScript for type-safe checks. Here's an example:

if (@Json.Encode(LoginModel.alert) === true) {
   // ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporated React component from Rails-assets.org into a Rails application

I have been trying to incorporate a react component from rails-assets.org into my Rails application. Currently, I am using the react-rails gem to write react view in my application. Now, I want to use other react components such as react-router, react-sel ...

Refreshing image does not reload

function updateimage(){ $("#fileimg").attr("src","path/to/image.jpg"); $('#fileimg').fadeIn('slow'); setTimeout(updateimage, 5000); } Greetings, I am trying to refresh an image every 5 seconds but it's not working as ...

Utilizing Dependency Injection in .NET8 to Inject Dual Instances of MongoDb Clients

I am seeking guidance on implementing Dependency Injection with .NET Core 3 to inject two instances of MongoDB Clients. I have a specific use case where I need to read data from Db1/collection1 and then save new information to Db2/collection2. In my startu ...

Having trouble with .animate() function?

Struggling to animate the position of my background image $(function() { $('#nav1').bind('click',function(event){ $('ul.nav').stop().animate({backgroundPosition: 'right top'}, 1000); }); $(function() { ...

Prevent the laser from continuing its incrementation cycle in JavaScript

If you want to see a live demonstration, simply copy the code into Notepad++ and run it in Chrome as an .html file. I encountered some difficulties when trying to display a working example using Snippet or CodePen, so unfortunately, I couldn't provide ...

The JavaScript script to retrieve the background color is malfunctioning

I am currently working on developing a highlighting feature for an HTML table that will dynamically change the row colors on mouseover. Below is the code snippet I have been using, but it seems to be experiencing some issues. Any assistance would be greatl ...

What benefits does using _.filter have over _.forEach when dealing with the task of evaluating a value and then outputting another value

As a newcomer to JavaScript, I rely heavily on eslint and plugins for guidance. My code is written for an environment with lodash 3.9.3 and must be compatible with Chrome 40, utilizing es5. Here's a snippet of my code: _.forEach(star.syst ...

Canceling the http post request while subscribing to a service

After wrestling with this issue for a whole week, I am still unable to successfully send a basic post request to the Heroku server using Angular HttpClient. I've meticulously defined all the services in the provider section of the main app module. Str ...

What is the process for accessing the C# code implementation in VSCode?

System Requirements: Visual Studio Code version: 1.63.2 (Universal) Operating System: MacOS Monterey 12.03 with M1 chip .NET version: 6.0.302 My background is primarily in Python, but I have been delving into C#, specifically ASP.NET Core 6, lately. Lat ...

How can you display variables within another variable in Vue?

Is it possible for Vue to render variables inside another variable? If not, how can I achieve this functionality? data() { return { SQL: { columns: ["id", "status", "post"], table: "users", limit: 10, query: "SELECT {{co ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

The React.js Mui Collapse component exclusively triggers animation during the transition while closing, without any animation when expanding

Whenever I implement the Collapse component from Mui library in my projects, I face an issue where the transition animation only works when closing the component (when in={false}). However, when opening the component, there is a delay before the animation ...

Display a modal popup form in ReactJS when a particular key is pressed

As a beginner in ReactJS, I am currently developing the frontend of a web application that requires multiple modal dialogues to be displayed based on specific key combinations. To achieve this functionality, I plan to utilize JQuery-UI for the modal dialog ...

What is the best way to merge several fetchMore functions within Apollo?

Can Apollo run multiple fetchMores simultaneously? I have a complex hook that executes two queries and combines their results into a single array. This is how it looks: export const useDashboardState = (collection: string) => { // Getting parameters ...

Dynamic Parameter (?) in NodeJS Sqlite WHERE IN Query Statement

In my Node application, I encountered an issue with using dynamic parameters in my SQLITE statements. Specifically, when trying to implement a WHERE IN query, no results were returned. This suggests that the dynamic parameter is being misinterpreted. Below ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

Validating Range Constraints

I am facing a dilemma with my GridView that contains a textbox in one of its fields. To ensure that the user enters only a single character "x", I have implemented a range validator: <asp:TextBox ID="txtMP3Master" runat="server" Text='<%# Eval( ...

Error: The XPath expression provided is invalid for use with the scrollIntoView function in Selenium

My task involves utilizing Python to extract data from a website that features a filter pane requiring scrolling. I came across a code snippet that aids in navigating through a list of elements by iterating through a loop. recentList = driver.find_element ...

Automatically generating web elements

Is there a more efficient way to generate .net code from a template to speed up development for developers who prefer not to write them in the IDE and compile them? I know I can create my own tool using reflection, but is there a simpler solution that buil ...

Best Javascript framework for ASP.NET MVC incorporating razor

Struggling to find the perfect JavaScript framework for ASP .NET MVC and razor? I decided to try out Angular 2, Aurelia, and AngularJS in a demo application. My experience shows that while Angular 2 and Aurelia can integrate with MVC and razor, they are ...