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

ASP.NET MVC点击按钮时显示加载图直至保存数据并跳转页面

解决表单提交时显示加载动画的问题

我明白你现在遇到的困扰:点击提交按钮后,想要显示加载图片直到数据保存完成并跳转页面,但现有的方法都没生效。别担心,我们可以通过AJAX异步提交表单的方式来完美解决这个问题——因为同步表单提交会直接刷新页面,加载动画根本来不及正常显示。

下面是具体的实现步骤:

1. 调整View页面代码

首先确保你的加载容器divLoading初始隐藏,并且给表单加上ID方便JS操作:

@using (Html.BeginForm("SaveCountry", "Country", FormMethod.Post, new { id = "countrySaveForm" }))
{
    <!-- 你的表单输入项,比如国家名称、代码等 -->
    @Html.TextBoxFor(m => m.CountryName)
    @Html.TextBoxFor(m => m.CountryCode)
    
    <button type="submit" class="btn btn-primary">保存国家</button>
}

<!-- 加载动画容器,初始隐藏,添加半透明背景增强视觉效果 -->
<div id="divLoading" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 9999;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center;">
        <img src="@Url.Content("~/Content/Images/loading-spinner.gif")" alt="正在保存..." />
        <p style="color: white; margin-top: 10px;">数据保存中,请稍候...</p>
    </div>
</div>

2. 添加JavaScript逻辑(两种方案可选)

我们需要拦截表单的默认提交行为,改用AJAX提交,这样就能完全控制加载动画的显示和隐藏:

方案一:使用jQuery(如果项目已引入jQuery)

$(document).ready(function() {
    $('#countrySaveForm').on('submit', function(e) {
        // 阻止表单默认同步提交
        e.preventDefault();
        
        // 显示加载动画
        $('#divLoading').show();
        
        // 获取表单数据
        var formData = $(this).serialize();
        
        // 发起AJAX请求
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: formData,
            success: function(response) {
                // 保存成功后跳转到目标页面(比如国家列表页)
                window.location.href = '@Url.Action("Index", "Country")';
            },
            error: function(xhr, status, error) {
                // 处理保存失败的情况,提示用户
                alert('保存失败:' + error);
                // 隐藏加载动画
                $('#divLoading').hide();
            }
        });
    });
});

方案二:原生JavaScript(无需依赖jQuery)

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('countrySaveForm');
    const loadingDiv = document.getElementById('divLoading');
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        loadingDiv.style.display = 'block';
        
        const formData = new FormData(form);
        
        fetch(form.action, {
            method: form.method,
            body: formData
        })
        .then(response => {
            if (response.ok) {
                // 保存成功,跳转页面
                window.location.href = '@Url.Action("Index", "Country")';
            } else {
                throw new Error('服务器返回错误');
            }
        })
        .catch(error => {
            alert(error.message);
            loadingDiv.style.display = 'none';
        });
    });
});

3. 调整Controller的SaveCountry方法

让控制器返回JSON结果,方便AJAX判断是否保存成功:

[HttpPost]
public ActionResult SaveCountry(CountryViewModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            // 执行数据库保存逻辑
            _countryRepository.Save(model);
            // 返回成功标识
            return Json(new { success = true });
        }
        catch (Exception ex)
        {
            // 捕获异常,返回失败信息
            return Json(new { success = false, error = ex.Message });
        }
    }
    // 表单验证失败,返回错误信息
    var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
    return Json(new { success = false, error = string.Join(";", errors) });
}

为什么之前的方法没生效?

大概率是因为你用了同步表单提交,点击提交后浏览器会立即刷新页面,加载动画刚显示就被页面跳转覆盖了,用户根本看不到。而AJAX异步提交会在后台处理请求,页面不会刷新,所以能稳定显示加载动画直到请求完成。

试试上面的方案,应该就能解决你的问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:47:13