You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap模态框的登录局部视图中显示‘Invalid login attempt’提示信息且不跳转到新登录页面?

Hey there! Let's fix this login error display issue so your modal stays intact while showing the "Invalid login attempt" message. Here's what's going wrong and how to fix it:

The Root Problem

Right now, your login form uses a standard synchronous POST request. When login fails and your action returns a PartialView("_Login", model), the browser treats that partial view as a full page and renders it directly—hence the jump to a new page instead of updating the modal. We need to switch to an AJAX-based submission to keep everything within the modal.

Step 1: Update the Frontend to Use AJAX Submission

First, make sure your login form has an ID, and add JavaScript to handle the form submit asynchronously. Also, wrap your partial view in a container so we can easily replace its content when errors occur.

<!-- Example Bootstrap Modal Structure -->
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Login</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <!-- Container for the login partial view -->
        <div id="loginModalContainer">
          @Html.Partial("_Login")
        </div>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function() {
  // Handle login form submission
  function handleLoginSubmit(e) {
    e.preventDefault();
    const form = $(this);
    
    $.ajax({
      url: form.attr('action'),
      type: form.attr('method'),
      data: form.serialize(),
      success: function(response) {
        if (typeof response === 'string') {
          // Login failed: replace modal content with updated partial view (with errors)
          $('#loginModalContainer').html(response);
          // Rebind the submit event since we replaced the form DOM element
          $('#loginForm').off('submit').on('submit', handleLoginSubmit);
        } else if (response.redirectUrl) {
          // Login succeeded: redirect to the intended page
          window.location.href = response.redirectUrl;
        }
      },
      error: function() {
        alert('Oops, something went wrong during login.');
      }
    });
  }

  // Bind the submit event initially
  $('#loginForm').on('submit', handleLoginSubmit);
});
</script>

Step 2: Adjust Your Backend Login Action

We need to modify the action to return JSON for successful logins (since AJAX can't automatically handle redirects) and keep returning the partial view for failures. Also, fix the ModelState.IsValid case to return the partial view instead of redirecting to the home page.

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        // Return the partial view to show validation errors in the modal
        return PartialView("_Login", model);
    }

    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            // Return JSON with redirect URL for AJAX to handle
            var redirectResult = RedirectToLocal(returnUrl);
            return Json(new { redirectUrl = redirectResult.Url });
        case SignInStatus.LockedOut:
            // Return the lockout partial view if you have one (adjust to fit your modal)
            return PartialView("Lockout");
        case SignInStatus.RequiresVerification:
            return Json(new { redirectUrl = Url.Action("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }) });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return PartialView("_Login", model);
    }
}

Step 3: Ensure Error Messages Show Up in the Partial View

Double-check that your _Login.cshtml partial view includes validation summaries to display the error message. Here's a quick example:

@model LoginViewModel

@using (Html.BeginForm("Login", "Account", new { returnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "loginForm" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-group">
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
    </div>
    <!-- Global error summary for the "Invalid login attempt" message -->
    @Html.ValidationSummary(true, "", new { @class = "text-danger mb-3" })
    
    <div class="form-group">
        @Html.CheckBoxFor(m => m.RememberMe)
        @Html.LabelFor(m => m.RememberMe)
    </div>
    
    <button type="submit" class="btn btn-primary">Login</button>
}

How This Works

  • AJAX submission prevents the browser from reloading the page.
  • On login failure, the action returns the updated _Login partial view with ModelState errors, which we inject back into the modal.
  • On success, we return a JSON object with the redirect URL, and the JavaScript handles the page jump.

内容的提问来源于stack exchange,提问作者devvab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:02:31