简体   繁体   English

用户登录后如何显示弹出消息?

[英]How can I show a pop-up message after an user is logged in?

I'm working on an asp.net core mvc website for a homework.我正在 asp.net 核心 mvc 网站上做作业。 The app is using identity server for login.该应用程序正在使用身份服务器进行登录。 I'm trying to show a pop-up alert after an user enters the correct credentials and presses the Login button(something like javascript alert).我试图在用户输入正确的凭据并按下登录按钮后显示一个弹出警报(类似于 javascript 警报)。 I've created a boolean property inside the.cs file which becomes true when an user succesfully logs in. In the.cshtml file I've added a script block which contains a function that shows an alert when the boolean property is true.我在 .cs 文件中创建了一个 boolean 属性,当用户成功登录时该属性变为真。在 .cshtml 文件中,我添加了一个包含 function 的脚本块,当 Z84E2C64F38F2DA27ZEA 属性为真时显示警报The issue is that the function is executed when the page is created(at that moment the property is false) even though I'm calling the function on button click.问题是 function 在创建页面时执行(此时属性为假),即使我在按钮单击时调用 function 。 Any suggestions which might be the 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();
        }
    }
}

Are you sure @LoginModel.alert gives out a JS-boolean?你确定@LoginModel.alert给出一个 JS-boolean 吗? Because it usually doesn't when writing JS with razor.因为在用 razor 编写 JS 时通常不会。

If the output is not exactly understood as boolean by Javascript at this point, it is "truthy".如果此时 output 没有被 Javascript 完全理解为 boolean,那就是“真实”。 Eg if it is parsed as a string, the condition is "true" for JS.例如,如果将其解析为字符串,则 JS 的条件为“真”。

In JS I would always suggest checking values with === , just to be on the type-safe side.在 JS 中,我总是建议使用===检查值,只是为了保证类型安全。 For example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM