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

ASP.NET MVC中登录失败后保持登录模态框开启的实现方法

解决方案

方案1:同步提交下的快速修复(无需修改提交方式)

问题根源是登录失败后页面刷新,模态框默认关闭,需在页面加载时自动重新打开模态框并显示错误。

  1. 确认模态框ID
    确保登录模态框外层容器带有id="LoginModal"(你的_LoginModal代码未显示外层,需补充):
<div id="LoginModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <!-- 你的_LoginModal里的modal-header、modal-body等内容 -->
        </div>
    </div>
</div>
  1. 在首页添加触发脚本
    在Index.cshtml中添加页面加载判断,当存在登录错误时自动打开模态框:
@section scripts {
    <script>
        $(document).ready(function() {
            @if(ViewBag.LoginError == 1)
            {
                $('#LoginModal').modal('show');
            }
        });
    </script>
}

或通过Model判断(更可靠,因为已将LoginModel传递回视图):

@if(!string.IsNullOrEmpty(Model?.ErrorMessage))
{
    <script>
        $(function() {
            $('#LoginModal').modal('show');
        });
    </script>
}

方案2:AJAX异步提交(推荐,体验更流畅)

这种方式避免页面刷新,模态框保持打开状态,直接显示错误信息。

  1. 修改登录表单的提交逻辑
    在_LoginModal.cshtml中添加AJAX提交脚本:
@section scripts {
    <script>
        $('#loginForm').submit(function(e) {
            e.preventDefault(); // 阻止默认表单刷新
            var $form = $(this);
            var $errorElement = $('.field-validation-error');

            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                success: function() {
                    // 登录成功,跳转首页
                    window.location.href = '@Url.Action("Index", "Home")';
                },
                error: function(xhr) {
                    // 显示错误信息
                    var errorMsg = xhr.responseJSON?.ErrorMessage || '登录失败';
                    $errorElement.text(errorMsg);
                    // 确保模态框处于打开状态
                    $('#LoginModal').modal('show');
                }
            });
        });
    </script>
}
  1. 修改控制器方法返回JSON
    更新Authorize方法,登录成功/失败时返回JSON而非视图:
[HttpPost]
public ActionResult Authorize(Logins LoginModel)
{
    var LoggedUser = db.Logins.SingleOrDefault(x => x.Username == LoginModel.Username && x.Password == LoginModel.Password);
    if (LoggedUser != null)
    {
        ViewBag.LoggedStatus = "In";
        ViewBag.LoginError = 0;
        Session["Username"] = LoggedUser.Username;
        return Json(new { success = true });
    }
    else
    {
        var errorMsg = "Login failed.";
        ViewBag.LoggedStatus = "Out";
        ViewBag.LoginError = 1;
        // 返回错误状态码和信息
        return Json(new { success = false, ErrorMessage = errorMsg }, HttpStatusCode.BadRequest);
    }
}

注意:确保项目已引入jQuery(Bootstrap模态框依赖jQuery)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:54:15