【问题标题】:What is the best way to centralize TempData success / error messages?集中 TempData 成功/错误消息的最佳方法是什么?
【发布时间】:2016-10-04 20:09:25
【问题描述】:

此时几乎每个控制器方法都会向视图返回带有 TempData 的成功/错误消息,如下所示:

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

我想将这个功能集中在一个简单的方法中,该方法可以从应用程序(控制器)的任何地方调用,那么将这个功能集中到一个可以重用的方法中的最佳方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 tempdata


    【解决方案1】:

    您可以为控制器创建扩展。在您的静态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";
         }
      }
    

    然后在你的操作方法中

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

    您也可以将成功和错误消息作为参数传递。 (但我个人认为这是不必要的,您应该将 TempData 保留在 ActionMethods 中)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      相关资源
      最近更新 更多