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

ASP.NET MVC FX 向其他Action传递错误消息不生效问题求助

问题修复方案

核心错误原因

你当前的问题是RedirectToAction传参时参数名不匹配,且Action入参类型设置错误,导致路由绑定失败,参数值没有正确传入Action方法。

需修改的两处代码:

  1. 修改Catch块内的跳转逻辑
    不需要将字符串强转为object,明确指定路由参数名即可:
catch (DbEntityValidationException ex)
{
    var err = new StringBuilder();
    foreach (var entityValidationErrors in ex.EntityValidationErrors)
    {
        foreach (var validationError in entityValidationErrors.ValidationErrors)
        {
            Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
            // 可以把属性名也拼进去,测试人员看的更清楚
            err.AppendLine($"属性:{validationError.PropertyName},错误:{validationError.ErrorMessage}");
            System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
        }
    }
    // 明确指定参数名,和ErrorMessage的入参名对应
    return RedirectToAction("ErrorMessage", "Employees", new { message = err.ToString() });
}
  1. 还原ErrorMessage Action的入参类型
    不需要用object作为入参,直接用字符串类型和参数名匹配即可:
public ActionResult ErrorMessage(string message)
{
    ViewBag.ErrorMessage = message;
    System.Diagnostics.Debug.WriteLine("Error message: " + message);
    // 你已经把错误信息存到ViewBag了,不需要再传参数给View
    return View();
}

额外优化建议

如果错误信息较长,直接通过URL传参可能触发长度限制,建议改用TempData存储错误信息,无需走URL传参:

  • Catch块写法:
TempData["ErrorMessage"] = err.ToString();
return RedirectToAction("ErrorMessage");
  • ErrorMessage Action写法:
public ActionResult ErrorMessage()
{
    ViewBag.ErrorMessage = TempData["ErrorMessage"]?.ToString();
    return View();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:27:05