2012-01-03 31 views
4

我有幾個操作方法與IList類型的參數。ASP.NET MVC - 當參數爲null時綁定空集合

public ActionResult GetGridData(IList<string> coll) 
{ 
} 

默認行爲是當沒有數據傳遞給操作方法參數爲null時。

有什麼辦法可以得到一個空的集合,而不是空的應用程序範圍?

回答

5

嗯,你可以做這一點:

coll = coll ?? new List<string>(); 

或者你需要實現一個模型綁定器,這將創建一個空的列表,而不是返回空的。例如:

public EmptyListModelBinder<T> : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
    var model = base.BindModel(controllerContext, bindingContext) ?? new List<T>(); 
    } 
} 

和有線起來就是:

ModelBinders.Binders.Add(typeof(IList<string>), new EmptyListModelBinder<string>()); 

我可能會堅持使用,雖然參數檢查...

+1

爲什麼要堅持空檢查?返回空集合而不是null是最佳做法。 – user49126 2012-01-03 10:12:01

+0

你爲什麼這麼想?如果'null'代表什麼是空列表代表什麼?如果您傳入null,您的控制器的單元測試會發生什麼?他們會失敗。你有一個公共方法,它構成了你的API的一部分,這意味着你應該參數檢查這些輸入。我不記得任何指導方針,說空列表比空更好... – 2012-01-03 10:15:36

+0

看看這裏http://stackoverflow.com/questions/1969993/is-it-better-to-return-null-or-空集 – user49126 2012-01-03 10:19:18

1

乾脆自己動手

public ActionResult GetGridData(IList<string> coll) 
{ 
    if(coll == null) 
     coll = new List<String>(); 
    //Do other stuff 
} 
+0

不幸的是,這將無法工作,因爲'新目錄( )'不是編譯時間常量。 – 2012-01-03 10:04:34

+0

噢,好的。我不知道。感謝您的提示。 – Maheep 2012-01-03 10:05:41

+0

刪除了第一個解決方案以避免混淆。 – Maheep 2012-01-03 10:09:25

相關問題