ajax ASP.NET MVC:如何在服务器端处理后显示成功确认消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13541225/
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
ASP.NET MVC: How to display success confirmation message after server-side processing
提问by Paul Taylor
I have a requirement to display a message confirming a successful database update in an ASP.NET MVC application. Currently the application only shows messages (using a ValidationSummary helper) when an error occurs. On a successful operation, the application currently redirects to a suitable point in the navigation.
我需要在 ASP.NET MVC 应用程序中显示一条消息,确认数据库更新成功。当前,应用程序仅在发生错误时显示消息(使用 ValidationSummary 助手)。成功操作后,应用程序当前重定向到导航中的合适点。
Goals are:
目标是:
- Display the confirmation message in an appropriate way
- Minimise user actions required to proceed after reading message
- Avoid an extra post / round-trip to display the message
- Minimise development effort and risk inserting a message at multiple points in the application
- 以适当的方式显示确认消息
- 尽量减少阅读消息后继续所需的用户操作
- 避免额外的帖子/往返来显示消息
- 最大限度地减少在应用程序中的多个点插入消息的开发工作和风险
My preference would be some sort of tool-tip type message display near the submit button and then a mechanism for removing the message and proceeding with the existing redirection after success.
我的偏好是在提交按钮附近显示某种工具提示类型的消息,然后是一种用于删除消息并在成功后继续现有重定向的机制。
That seems to suggest an Ajax call rather than the existing HTTP POST to submit the form. How would I go about this?
这似乎建议使用 Ajax 调用而不是现有的 HTTP POST 来提交表单。我该怎么办?
回答by SimonGates
I Would use TempData["key"]
我会用 TempData["key"]
This is like ViewData["key"]however the data persists for the next HttpRequest and is disposed automatically by asp.net after this
ViewData["key"]然而,这就像数据在下一个 HttpRequest 中持续存在,并在此之后由 asp.net 自动处理
So you can do this.
所以你可以这样做。
Controller Action
控制器动作
[HttpPost]
public ActionResult SomePostAction(SomeViewModel vm)
{
if(ModelState.IsValid) // Is User Input Valid?
{
try
{
CommitData();
TempData["UserMessage"] = new MessageVM() { CssClassName = "alert-sucess", Title = "Success!", Message = "Operation Done." };
return RedirectToAction("Success");
}
catch(Exception e)
{
TempData["UserMessage"] = new MessageVM() { CssClassName = "alert-error", Title = "Error!", Message = "Operation Failed." };
return RedirectToAction("Error");
}
}
return View(vm); // Return View Model with model state errors
}
_Layout.cshtml
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
</head>
<body>
@if(TempData["UserMessage"] != null)
{
var message = (MessageVM)TempData["UserMessage"];
<div class="alert @message.CssClassName">
<strong>@message.Title</strong>
@message.Message
</div>
}
@RenderBody()
</body>
</html>
More Info: http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html
更多信息:http: //www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html
回答by Anand
On a successful operation ,you just store the success message description into ViewBag like as
成功操作后,您只需将成功消息描述存储到 ViewBag 中,就像
ViewBag.successMessage="Success"
then in view check the ViewBag value is null or not? through javascript ,if not null show the message in Div
然后在视图中检查 ViewBag 值是否为空?通过javascript,如果不为null,则在Div中显示消息
if('@ViewBag.successMessage'!="")
{
$('#divSuccessMessage').show();
}
else
{
$('#divSuccessMessage').hide();
}
default in page load hide the div
页面加载中的默认隐藏div
回答by RohitWagh
the following links might help you (posting links as it would require better explanation):
以下链接可能对您有所帮助(发布链接需要更好的解释):
http://msdn.microsoft.com/en-us/magazine/ff797575.aspx
http://msdn.microsoft.com/en-us/magazine/ff797575.aspx
回答by Christ A
As others mentioned, TempDatais one of the most straight forward options to use. Its main drawback in regular ASP.NET in my opinion is that it uses the session storage in to store its contents. 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是最直接的选项之一。在我看来,它在常规 ASP.NET 中的主要缺点是它使用会话存储来存储其内容。这意味着您需要做额外的工作才能让它在网络场上运行,或者您首先需要打开会话。
TempDatais a string based dictionary you can put anything in it, and by default get it out only once on any later request. Before calling RedirectToAction()you set your message and on the next request you check for messages and display them. By retrieving the messages they are automatically deleted at the end of the request.
TempData是一个基于字符串的字典,您可以将任何内容放入其中,并且默认情况下仅在以后的任何请求中将其取出一次。在呼叫之前RedirectToAction()设置您的消息,并在下一个请求中检查消息并显示它们。通过检索消息,它们会在请求结束时自动删除。
As an alternative you could use cookies for transporting the message between the two requests. Essentially you could either roll your own solution, or implement a custom ITempDataProviderwhich transports the contents of TempDatavia cookies. Given that the messages are short, the performance impact is minimal. Note that you need to properly secure cookies.
作为替代方案,您可以使用 cookie 在两个请求之间传输消息。本质上,您可以推出自己的解决方案,也可以实现通过 cookieITempDataProvider传输内容的自定义TempData。鉴于消息很短,对性能的影响很小。请注意,您需要正确保护 cookie。
I was facing the same problem you did and created a solution for it called FlashMessage. It's available on NuGet. Usage is simple: you simply queue a message before you call RedirectToAction()as follows:
我遇到了和你一样的问题,并为它创建了一个名为FlashMessage的解决方案。它在NuGet上可用。用法很简单:您只需在调用之前将消息排队RedirectToAction(),如下所示:
FlashMessage.Confirmation("Your message");
return RedirectToAction("AdminUsers", "Admin");
In your view you include the following statement to render any previously queued messages:
在您的视图中,您包含以下语句以呈现任何先前排队的消息:
@Html.RenderFlashMessages()

