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:
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?
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
On a successful operation ,you just store the success message description into ViewBag like as
ViewBag.successMessage="Success"
then in view check the ViewBag value is null or not? through javascript ,if not null show the message in Div
if('@ViewBag.successMessage'!="") { $('#divSuccessMessage').show(); } else { $('#divSuccessMessage').hide(); }
default in page load hide the div
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With