asp.net-mvc 使用 RedirectToAction 时如何在视图中显示成功消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27886084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:21:55  来源:igfitidea点击:

How to show success message in view when RedirectToAction used

asp.net-mvc

提问by Mukesh Kumar

I am working on MVC3 project and I want to show a message when I use RedirectToAction in view. I have used ViewBag but it is not working.

我正在处理 MVC3 项目,我想在视图中使用 RedirectToAction 时显示一条消息。我使用过 ViewBag 但它不起作用。

Please anybody help me.

请任何人帮助我。

回答by Ritesh Kumar

you can use TempData to show the message

您可以使用 TempData 来显示消息

in your View

在您的视图中

@if (TempData["Success"] != null)
{
 <p class="alert alert-success" id="successMessage">@TempData["Success"]</p>
}

and in your controller after success

成功后在您的控制器中

TempData["Success"] = "Added Successfully!";
return RedirectToAction("actionname", "controllername");

回答by Christ A

The TempDatacontroller property can be used to achieve this kind of functionality. It's disadvantage is that it uses the session storage in the background. This means that you'll have extra work getting it to function on a web farm, or that you need to turn on sessions in the first place.

TempData控制器属性可以用来实现这种功能。它的缺点是它在后台使用会话存储。这意味着您需要做额外的工作才能让它在网络场上运行,或者您首先需要打开会话。

Alternatively you could use cookies if you only need to transport a short message. Doing so does require you to properly secure the cookie in order to prevent tampering. MachineKey.Protect()can help you do this.

或者,如果您只需要传输一条短消息,您可以使用 cookie。这样做确实需要您正确保护 cookie 以防止篡改。MachineKey.Protect()可以帮助你做到这一点。

I was facing the same problem you did and created a solution for it called FlashMessage. Perhaps this could save you some work. It's available on NuGetas well.

我遇到了和你一样的问题,并为它创建了一个名为FlashMessage的解决方案。也许这可以为您节省一些工作。它也可以在NuGet上使用。

Using FlashMessageis easy. You simply queue a message before you call RedirectToAction()as follows:

使用FlashMessage很容易。您只需在调用之前将消息排队RedirectToAction(),如下所示:

// User successfully logged in
FlashMessage.Confirmation("You have been logged in as: {0}", user.Name);
return RedirectToLocal(returnUrl);

In your view you include the following statement to render any previously queued messages:

在您的视图中,您包含以下语句以呈现任何先前排队的消息:

@Html.RenderFlashMessages()