ASP.NET MVC:如何在服务器端处理后显示成功确认消息 [英] ASP.NET MVC: How to display success confirmation message after server-side processing

查看:318
本文介绍了ASP.NET MVC:如何在服务器端处理后显示成功确认消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示一条消息,以确认ASP.NET MVC应用程序中的数据库更新成功。当前,应用程序仅在发生错误时显示消息(使用ValidationSummary帮助器)。成功完成操作后,应用程序当前将重定向到导航中的适当点。

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.

目标是:


  • 以适当的方式显示确认消息

  • 最小化阅读消息后需要进行的用户操作

  • 避免发表过多帖子/往返以显示消息

  • 最小化开发工作,并冒着在应用程序中多个点插入消息的风险

  • 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.

这似乎建议使用Ajax调用而不是现有的HTTP POST来提交表单。我将如何处理?

That seems to suggest an Ajax call rather than the existing HTTP POST to submit the form. How would I go about this?

推荐答案

我将使用 TempData [ key]

这就像 ViewData [ key] 一样,但是对于下一个HttpRequest和在此之后,asp.net会自动将其丢弃。

This is like ViewData["key"] however the data persists for the next HttpRequest and is disposed automatically by asp.net after this

因此您可以执行此操作。

So you can do this.

控制器操作

[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

<!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>

更多信息: http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html

这篇关于ASP.NET MVC:如何在服务器端处理后显示成功确认消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆