我有幾個操作方法與IList類型的參數。ASP.NET MVC - 當參數爲null時綁定空集合
public ActionResult GetGridData(IList<string> coll)
{
}
默認行爲是當沒有數據傳遞給操作方法參數爲null時。
有什麼辦法可以得到一個空的集合,而不是空的應用程序範圍?
我有幾個操作方法與IList類型的參數。ASP.NET MVC - 當參數爲null時綁定空集合
public ActionResult GetGridData(IList<string> coll)
{
}
默認行爲是當沒有數據傳遞給操作方法參數爲null時。
有什麼辦法可以得到一個空的集合,而不是空的應用程序範圍?
嗯,你可以做這一點:
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>());
我可能會堅持使用,雖然參數檢查...
爲什麼要堅持空檢查?返回空集合而不是null是最佳做法。 – user49126 2012-01-03 10:12:01
你爲什麼這麼想?如果'null'代表什麼是空列表代表什麼?如果您傳入null,您的控制器的單元測試會發生什麼?他們會失敗。你有一個公共方法,它構成了你的API的一部分,這意味着你應該參數檢查這些輸入。我不記得任何指導方針,說空列表比空更好... – 2012-01-03 10:15:36
看看這裏http://stackoverflow.com/questions/1969993/is-it-better-to-return-null-or-空集 – user49126 2012-01-03 10:19:18