Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

ajax - ASP.NET MVC: How to display success confirmation message after server-side processing

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I Would use TempData["key"]

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...