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

如何在ASP.NET MVC 5的Html.BeginForm中触发ajaxStart与ajaxStop

解决方案:Html.BeginForm提交时显示等待光标

针对你的ASP.NET MVC5项目,推荐以下几种低侵入性的方案,无需逐个修改159个视图页面:

方案1:全局监听表单提交事件(最推荐)

利用布局页Shared_ConsoleLayout.cshtml的全局脚本,监听所有非Ajax表单的提交事件,自动触发等待光标显示,页面加载完成后自动隐藏。

步骤:

  1. 在布局页的脚本区域添加以下代码:
// 监听所有非Ajax表单的提交事件
$(document).on('submit', 'form:not(.ajax-form)', function(e) {
    // 先验证表单(适配jQuery Validate,MVC默认使用)
    const $form = $(this);
    if ($form.data('validator') && !$form.valid()) {
        return; // 验证不通过,不显示加载状态
    }
    
    // 显示你的等待光标容器(替换成你已有的loading元素ID)
    $('#loadingOverlay').show();
    // 或者给body添加加载类来控制光标/遮罩
    // $('body').addClass('loading');
});

// 页面加载完成后隐藏等待状态
$(function() {
    $('#loadingOverlay').hide();
    // $('body').removeClass('loading');
});
  1. 如果你有部分表单已经通过Ajax处理(不需要重复触发),给这些表单添加ajax-form类:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { @class = "ajax-form" }))
{
    // 表单内容
}

方案2:自定义HtmlHelper扩展(批量替换场景)

如果希望统一管理表单的加载逻辑,可以封装一个自定义的BeginForm扩展方法,自动注入提交事件:

步骤:

  1. 在项目的Helpers文件夹中添加扩展类:
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class FormLoadingExtensions
{
    public static MvcForm BeginFormWithLoading(this HtmlHelper htmlHelper)
    {
        return htmlHelper.BeginForm(null, null, FormMethod.Post, new { onsubmit = "showLoading(); return true;" });
    }

    // 重载适配其他BeginForm参数(如指定Action/Controller)
    public static MvcForm BeginFormWithLoading(this HtmlHelper htmlHelper, string actionName, string controllerName)
    {
        return htmlHelper.BeginForm(actionName, controllerName, FormMethod.Post, new { onsubmit = "showLoading(); return true;" });
    }

    // 更多重载根据需求添加
}
  1. 在视图中替换原有的Html.BeginForm为Html.BeginFormWithLoading:
@using (Html.BeginFormWithLoading("Query", "Data"))
{
    // 表单内容
}
  1. 在布局页定义showLoading函数:
function showLoading() {
    $('#loadingOverlay').show();
}

方案3:CSS配合body类控制光标

如果只需要全局等待光标样式,无需遮罩,可以用CSS类实现:

步骤:

  1. 在全局CSS中添加:
body.loading {
    cursor: wait;
    /* 可选:添加半透明遮罩 */
    /* position: relative; */
}
/* 可选遮罩样式 */
body.loading::after {
    content: "";
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255,255,255,0.7);
    z-index: 9999;
}
  1. 在布局页脚本中添加:
$(document).on('submit', 'form:not(.ajax-form)', function(e) {
    const $form = $(this);
    if ($form.data('validator') && !$form.valid()) return;
    
    $('body').addClass('loading');
});

$(function() {
    $('body').removeClass('loading');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:57:31