J. Newb J. Newb - 2 months ago 8
C# Question

What is the best way to centralize TempData success / error messages?

At this moment almost every controller method will return success / error messages with TempData to the view like this:

if (result) {
TempData["messageSuccess"] = "Some nice success message";
} else {
TempData["messageError"] = "Some nice error message";
}


I want to centralize this functionality somewhere in a simple method which is callable from anywhere in the application (controllers), so what is the best way to centralize this into a method which can be reused?

Answer

You can create an extension for the controller. Add the below method in one of your static UtilityClass.

  public static void SetTempDataMessages(this Controller controller, bool result)
  {
     if (result) 
     {
        controller.TempData["messageSuccess"] = "Some nice success message";
     } 
     else 
     {
        controller.TempData["messageError"] = "Some nice error message";
     }
  }

Then in your action method

public ActionResult Index()
{
    var result = true;
    this.SetTempDataMessages(result);
    return View();
}

You can pass the success and error messages as parameters as well. (But I personally think this is unnecessary and you should keep your TempData in your ActionMethods)