2016-06-08 57 views
-1
public JsonResult GetReport(string reportSelected, string firstDateGiven) 
     { 
      _context = new ReportDB(); 

      var theResults = 
        miPolicyTransactions.Select(
         x => 
          new 
          { 
           PolicyReference = x.PolicyReference, 
           TransactionType = x.TransactionType 
           ... 
           }).ToList(); 

       var theadColumns = new[] 
       { 
        new {columnName = "Policy Reference"}, 
        new {columnName = "Transaction Code"} 
        ... 
       }.ToList(); 

       return Json(new { data = theResults, columns= theadColumns }, JsonRequestBehavior.AllowGet); 
      } 

以上是我從哪些作品開始的,但我已經使用了詞典func來簡化調用並創建其他內容。如何將匿名列表從靜態方法傳遞給調用方法?

private Dictionary<string, Func<IReportDB, string, JsonResult>> functions = new Dictionary<string, Func<IReportDB, string, JsonResult>> 
       { 
        { "New Business by Agent last 3 Months(set)", NewBusinessAgentLast3Month},     

        { "New Business by Agent last 7 days (set)", SomeOtherMethodName} 
        }; 

private static JsonResult NewBusinessAgentLast3Month(IReportDB context, string parameters) 
     { 

     _context = new ReportDB(); 

     var theResults = 
       miPolicyTransactions.Select(
        x => 
         new 
         { 
          PolicyReference = x.PolicyReference, 
          TransactionType = x.TransactionType 
          ... 
          }).ToList(); 

      var theadColumns = new[] 
      { 
       new {columnName = "Policy Reference"}, 
       new {columnName = "Transaction Code"} 
       ... 
      }.ToList(); 

      return ?????????????????????????? 

我得到

一個對象引用是所必需的非靜態字段,方法,屬性 錯誤我不能返回一個JSON對象。無法在靜態上下文中訪問非靜態Json。

我能避免爲每個具體類型列表中創建一個具體類型,但還是反過來匿名列表來調用方法傳遞給被作爲在我的Jquery使用的文件一個JsonResult回來了?你會使用列表還是有另一種方式?

+0

你不能讓這些功能變成靜態的嗎? –

+0

基本上沒有,因爲這破壞了客戶需要的OOP。總是我只有靜態方法作爲Dictionary 堅持他們(否則拋出一個錯誤)。 –

+0

你是說你得到一個編譯錯誤,或運行時異常?當你試圖在字典初始化非statc的Funcs? –

回答

1

你應該改變你的功能(如NewBusinessAgentLast3Month)返回object。您應該將此值傳遞給Controller.Json方法,該方法將創建一個JsonResult,您可以從控制器返回。

代碼中的問號應該用您在重構之前使用的匿名類型替換。

+0

我走動了,這實質上是@Martins的建議。非常感謝你。 –

相關問題