How to fix redirection with the use of sweetalert2 javascript in .NET MVC Identity?

MiKhel Navarra 20 Reputation points
2023-12-11T06:34:10.7966667+00:00

After the user has logged in? The error message displays: No webpage was found for the web address: https://localhost:44338/Identity/Account/Index

I tried this code in the OnPostAsync in login.cshtml.cs
and also to my login.cshtml

 $(document).ready(function () {
     // This script will be executed when the document is ready

     console.log("JavaScript is running!"); // Add this line to log a message to the console

     // Intercept the form submission
     $("#account").submit(function (e) {
         // Prevent the default form submission
         e.preventDefault();

         // Your existing AJAX call or form submission logic here

         // Simulate a successful login for demonstration purposes
         var fakeResult = { Succeeded: true };

         // Check if the login was successful
         if (fakeResult.Succeeded) {
             console.log("Login successful!"); // Add this line to log a message to the console

             // Assuming you have some way of determining the user's role
             var isAdmin = true; // Replace this with your actual logic to check if the user is an admin

             // Show SweetAlert for successful login
             Swal.fire({
                 title: 'Successfully Logged In',
                 icon: 'success',
                 showConfirmButton: true
             }).then(function () {
                 console.log("SweetAlert displayed!"); // Add this line to log a message to the console

                 // Redirect to the appropriate page based on the user's role
                 window.location.href = 'Index'; // Replace with the actual URL

                 // Show/hide the dropdown based on the user's role
                 if (isAdmin) {
                     console.log("User is an admin!"); // Add this line to log a message to the console
                     $(".admin-dropdown").removeClass("d-none");
                 } else {
                     console.log("User is not an admin!"); // Add this line to log a message to the console
                     $(".admin-dropdown").addClass("d-none");
if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");

    // Include SweetAlert2 script in TempData
    TempData["SweetAlertScript"] = "$('#login-submit').click(function () {" +
                       "    Swal.fire({" +
                       "        title: 'Successfully Logged In'," +
                       "        icon: 'success'," +
                       "        showConfirmButton: true" +
                       "    });" +
                       "});";
    TempData["SweetAlertType"] = "success";

    // Log TempData values for debugging
    _logger.LogInformation($"SweetAlertMessage: {TempData["SweetAlertMessage"]}");
    _logger.LogInformation($"SweetAlertType: {TempData["SweetAlertType"]}");

    // Redirect to the desired URL
    return LocalRedirect(returnUrl ?? Url.Action("Index", "Home"));
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
{count} votes

Accepted answer
  1. Anonymous
    2023-12-12T07:45:17.5466667+00:00

    Hi,@MiKhel Navarra

    As soon as I logged in and then the sweetalert pops up, I still can't get to the view of default page located in my Shared folder that i expect to appear

    It indicates you haven't authenticated at all,

    Identity is based on Cookie Authentication,you have to send a real request to your backend and call PasswordSignInAsync method to append required cookie to response

    a minimal example with ajax call:

    <script>
        $("#account").submit(
            function (e) {
                var form = $('#account')[0];
                var data = new FormData(form);
                console.log(data);
                e.preventDefault();            
                $.ajax({
                    url: 'login',
                    method: 'POST',                
                    data: data,
                    enctype: 'multipart/form-data',
                    processData: false,
                    contentType: false,
                    success: function (result, status, jqXHR) {
    
                        if (result.message == "success") 
                        {
                            Swal.fire({
                                title: 'Successfully Logged In',
                                icon: 'success',
                                showConfirmButton: true
                            })
                                .then(function () {
                                    console.log("SweetAlert displayed!"); // Add this line to log a message to the console
                                    // Redirect to the appropriate page based on the user's role
                                    window.location.href = '/Home/Index';
                                })
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                       
                    }
                });
            }
        )
    </script>
    

    Since you would redirect to another page/handle bad request in juqery codes,you don't need to redirect in your backend

    C# codes:

     public async Task<IActionResult> OnPostAsync(string? returnUrl )
     {
         returnUrl = Url.Action("Index", "Home");
    
         ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
    
         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)
             {
                 _logger.LogInformation("User logged in.");
                 //return LocalRedirect(returnUrl);
                 return new OkObjectResult(new {message="success"});
             }
            ........
         }
    
         // If we got this far, something failed, redisplay form
         return BadRequest();
     }
    

    The result:

    12.12


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Ruikai Feng

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.