ASP.NET MVC: How to display success confirmation message after server-side processing
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
How to show success message in view when RedirectToAction used
you can use TempData to show the message
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");
ASP.NET MVC Show success message
One way would be to use TempData:
[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
_db.DeleteObject(ArticleToDelete);
_db.SaveChanges();
TempData["message"] = ""Lorem ipsum article has been deleted";
return RedirectToAction("Index");
}
and inside the Index
action you could fetch this message from TempData and make use of it. For example you could pass it as a property of your view model which will be passed to the view so that it can show it:
public ActionResult Index()
{
var message = TempData["message"];
// TODO: do something with the message like pass to the view
}
UPDATE:
Example:
public class MyViewModel
{
public string Message { get; set; }
}
and then:
public ActionResult Index()
{
var model = new MyViewModel
{
Message = TempData["message"] as string;
};
return View(model);
}
and inside the strongly typed view:
<div><%: Model.Message %></div>
How to show success message after insertion through form submitting
Using TempData is ideal for the Post-Redirect-Get pattern.
Your Post Action:
[HttpPost]
public ActionResult Create(string txthospitalname, int city)
{
var hospitals = new Hospital()
{
Name = txthospitalname,
FKCityID = city,
CreatedAt = DateTime.Now,
CreatedBy = 1,
};
_db.Hospitals.Add(hospitals);
_db.SaveChanges();
TempData["Success"] = true;
return RedirectToAction("Create");
}
Your Get Action:
[HttpGet]
public ActionResult Create()
{
ViewBag.Success = TempData["Success"] as bool;
return View();
}
Your View:
@if (ViewBag.Success != null && ViewBag.Success)
{
<h2> Your Success Message Here</h2>
}
@using (Html.BeginForm("Create", "Hospital", FormMethod.Post,
new {enctype = "multipart/form-data", id = "hospitalform"}))
{
//Text Fields
}
how to popup successful message after sending the message in controller, using c#, MVC
Make you return object example like This
public class ServerResponse
{
public string ErrorMessage {get; set;}
public string SuccessMessage {get; set;}
}
And then
public async Task<ActionResult> GetEnquiredData(string FirstName, string LastName, string Email, string PhoneNumber, string TravelCalendar, string TravelNights, string TravelMonth, string TNoAdults, string TNoChildren, string SpecialOc, string GettoKnow, string TCUKMember, string Tdate, string Tprice, string byemail, string dealRef, string ConTime)
{
var serverResponse = new ServerResponse();
try { //Send Email here
serverResponse.SuccessMessage = "Success!";
}
catch (Exception ex)
{
serverResponse.ErrorMessage= $"Error! + {ex.Message}";
}
return Json(serverResponse, JsonRequestBehaviour.AllowGet);
}
After it check via ajax what server responsed. And show message!
Hope it helps
js
$.ajax({
url : /YourURL/GetEnquiredData,
data : {your data}
}).success(function(response)
{ if (response.ErrorMessage!=null)
{
showError(response.ErrorMessage):
}
else {
showSucess(response.SuccessMessage);
}
});
Related Topics
How to Return a File (Filecontentresult) in ASP.NET Webapi
Merge Multiple Lists into One List With Linq
How to Make a Soap/Wsdl Client in C#
C# Check the Empty or Null Value in All Datatable Values
How to Download Image from Url
Sending Array of Bytes from Client to Server
How to Upload File to Server With Http Post Multipart/Form-Data
Asp.Net Core Identity Successful Login Redirecting Back to Login Page
How to Calculate Sum (Total) of Datatable Columns Using C#
Convert Byte Array to Wav File
Cannot Access a Closed Stream of a Memorystream, How to Reopen
How to Store List of Data from Database to Arraylist or List in C#
Returning a File to View/Download in ASP.NET MVC
Best Way to Check If a Data Table Has a Null Value in It
C# - Comparing Items Between 2 Lists
C# How to Split a List in Two Using Linq