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

ASP.NET Core:返回弹窗后页面不刷新问题及优化方案咨询

问题分析与解决方案

你的问题出在同时使用Response.WriteAsync和重定向:当你调用Response.WriteAsync时,已经开始向HTTP响应流写入内容,后续返回的RedirectToPage无法正确发送重定向的3xx状态码和Location头,浏览器只会执行你写入的alert脚本,不会触发页面重定向,导致页面不刷新。

下面是两种更规范的实现方式:

方式一:使用TempData传递提示信息(推荐)

通过TempData将提示消息传递到目标页面,在页面加载时渲染弹窗脚本,既保留重定向逻辑,又能显示用户反馈。

后端代码修改

public async Task<IActionResult> OnPostButton_Yes(IFormCollection data) 
{ 
    var inputSkill = Request.Form["fertigkeitensuchen"];

    var item = new SubCategories
    {
        IsSkill = true,
        BelongsToUserId = userId,
        ValueGer = inputSkill.ToString(),
        BelongsToCategoryId = currentcategoryId
    };

    await new RemoteSubCategoriesService().SaveItemAsync(item);

    // 将提示消息存入TempData,它会在一次请求后自动过期
    TempData["SuccessAlert"] = "Skill wurde angelegt, du kannst diesen nun auswählen!";

    return RedirectToPage("../Jobs/Skills", "UserId", new { id = userId, categoryId = currentcategoryId });
}

前端视图(Skills.cshtml)添加脚本

在目标页面的HTML中,检查TempData是否存在消息,若存在则渲染alert脚本:

@if (TempData["SuccessAlert"] != null)
{
    <script>
        alert('@Html.Raw(TempData["SuccessAlert"])');
    </script>
}

方式二:通过查询参数传递提示信息

如果不想使用TempData,可以将消息作为查询参数附加到重定向URL,在目标页面读取并显示。这种方式的缺点是消息会暴露在URL中,且需要处理特殊字符编码。

后端代码修改

public async Task<IActionResult> OnPostButton_Yes(IFormCollection data) 
{ 
    // 省略业务逻辑代码...

    var message = "Skill wurde angelegt, du kannst diesen nun auswählen!";
    // 将消息作为查询参数传递
    return RedirectToPage("../Jobs/Skills", new { 
        id = userId, 
        categoryId = currentcategoryId, 
        alertMessage = Uri.EscapeDataString(message) 
    });
}

前端视图(Skills.cshtml)添加脚本

@if (!string.IsNullOrEmpty(Request.Query["alertMessage"]))
{
    <script>
        alert('@Html.Raw(Uri.UnescapeDataString(Request.Query["alertMessage"]))');
    </script>
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:02:51