c# - 使用 TempData 从帮助程序类进行 MVC 重定向

标签 c# asp.net-mvc asp.net-mvc-4 redirect tempdata

在我的 _Layout.cshtml 中,我有一些用于显示消息的 div。

<div>@TempData["SuccessMessage"]</div>
<div>@TempData["WarningMessage"]</div>
<div>@TempData["ErrorMessage"]</div>

我正在尝试创建一个全局重定向帮助程序类来显示这些消息:

MessageHelper.cs

public static RedirectResult RedirectWithMessage(Controller controller, string messagetype, string url, string message)
{
    controller.ViewData[messagetype] = message;
    return (new RedirectResult(url));
}

从我的 Controller :

return RedirectWithMessage(this, "SuccessMessage", "~/good", "Looks good");
return RedirectWithMessage(this, "WarningMessage", "~/warning", "Ooops a warning");
return RedirectWithMessage(this, "ErrorMessage", "~/error", "Danger an error");

我得到了重定向,但没有来自 TempData 的消息。

我已经在 Controller 中成功完成了此操作,使用:

private RedirectResult RedirectWithMessage(string messagetype, string url, string message)
{
    TempData[messagetype] = message;
    return Redirect(url);
}

非常感谢任何帮助...

最佳答案

你尝试过吗:

controller.TempData[messagetype] = message;

ViewData 不是您的布局所寻找的内容。

也许我错过了一些东西。

关于c# - 使用 TempData 从帮助程序类进行 MVC 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28205226/

相关文章:

c# - 使用 LINQ to Entity Framework 进行复杂字符串匹配

c# - StreamReader 问题

c# - 字符/字符串比较

c# - 如何告诉 ASP.Net MVC 从 JSON 反序列化的所有传入日期都应该是 UTC?

c# - 缺少 Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint 的编译错误

c# - Asp.Net MVC4中的Javascript/Jquery弹出窗口

asp.net-mvc - MVC 多表一模型

c# - 拼写出来的数字 (int) 的打印值

html - 如何在for循环中从右到左文本?

asp.net-mvc - WebAPI Controller 中的 MVC 路由