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

ASP.NET MVC中提交按钮执行后如何用Sweet Alert显示提示消息?

解决ASP.NET MVC提交后显示成功提示框的问题

问题根源

你当前的onclick="mostrarAlerta()"会在点击按钮立即触发提示框,但随后表单提交会导致页面刷新,提示框自然消失。要实现"数据处理完成后显示提示",需要让提示框在服务器处理完成、页面重新加载后再触发。

解决方案步骤

1. 控制器中传递处理状态

在CargarSQLServer控制器方法里,数据处理成功后通过TempData标记成功状态:

public ActionResult CargarSQLServer(YourModel model)
{
    // 执行数据库上传逻辑
    bool isSuccess = true; // 替换为实际处理结果判断
    
    if (isSuccess)
    {
        TempData["ProcessSuccess"] = true;
    }
    
    // 返回原视图(或根据需求跳转)
    return View("YourViewName");
}

2. 修改提交按钮

移除按钮上的onclick事件,避免提前触发提示:

<input type="submit" value="Procesar Datos" class="btn btn-secondary" formaction="/File/CargarSQLServer" />

3. 调整脚本逻辑

在视图的脚本区域,添加页面加载时的状态检查,并为提示框添加4秒自动关闭的计时器:

@section Scripts {
<script>
    function mostrarAlerta() {
        swal({
            title: "Actualización Exitosa",
            text: "Procesamiento de datos realizado correctamente",
            icon: "success",
            button: false,
            timer: 4000, // 4秒后自动关闭
            timerProgressBar: true // 可选:显示倒计时进度条
        });
    };

    // 页面加载完成后,检查是否需要显示提示
    @if (TempData["ProcessSuccess"] != null && (bool)TempData["ProcessSuccess"])
    {
        <text>
            mostrarAlerta();
        </text>
    }
</script>
}

原理说明

  • TempData会在服务器处理完成后,将成功状态传递到下一次请求的视图中
  • 页面重新加载后,脚本检测到TempData中的成功标记,才触发提示框
  • 通过timer:4000设置提示框停留4秒,button:false确保提示框无交互按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:10:29