Asp.net-Mvc

在 Helper 錯誤中使用 TempData:名稱“TempData”在目前上下文中不存在

  • March 12, 2016

我想在我的助手中訪問TempData以獲取Flash 消息(如在 ruby​​ 中)

我得到一個執行時錯誤

The name 'TempData' does not exist in the current context

我的 Flash.cshtml 如下

@helper Show() 
{
   var message = "test message";
   var className = "info";

   if (TempData["info"] != null)
   {
       message = TempData["info"].ToString();
       className = "info";
   }
   else if (TempData["warning"] != null)
   {
       message = TempData["warning"].ToString();
       className = "warning";
   }
   else if (TempData["error"] != null)
   {
       message = TempData["error"].ToString();
       className = "error";
   } 

   <script>
       $(document).ready(function () {
           $('#flash').html('@HttpUtility.HtmlEncode(message)');
           $('#flash').toggleClass('@className');
           $('#flash').slideDown('slow');
           $('#flash').click(function () { $('#flash').toggle('highlight') });
       });
   </script>
}

在我的佈局中

<section id="main">
   @Flash.Show() 
   <div id="flash" style="display: none"></div>
   @RenderBody()
</section>

TempData 屬於ControllerBase作為控制器基類的類,它不能被沒有控制器的共享視圖訪問,

一種可能的解決方法是將控制器傳遞給您的幫助方法或通過 HtmlHelper 訪問它。

@helper SomeHelper(HtmlHelper helper)
{
 helper.ViewContext.Controller.TempData
}

只需將TempData傳遞給您的助手。

在您的佈局中對助手的呼叫將如下所示。

@Flash.Show(TempData)

您的 Flash.cshtml 助手將如下所示。

@helper Show(System.Web.Mvc.TempDataDictionary tempData)
{
   // The contents are identical to the OP's code,
   // except change all instances of TempData to tempData.
}

引用自:https://stackoverflow.com/questions/8762709