加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC – 当参数为null时绑定空集合

发布时间:2020-12-16 06:46:46 所属栏目:asp.Net 来源:网络整理
导读:我有几个动作方法与IList类型的参数. public ActionResult GetGridData(IListstring coll){} 默认行为是当没有数据传递给action方法时参数为null. 有没有办法获得一个空集合而不是null应用程序? 解决方法 好吧,你可以这样做: coll = coll ?? new Liststrin
我有几个动作方法与IList类型的参数.

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

默认行为是当没有数据传递给action方法时参数为null.

有没有办法获得一个空集合而不是null应用程序?

解决方法

好吧,你可以这样做:

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

或者您需要实现一个ModelBinder,它将创建一个空列表而不是返回null.例如.:

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>());

我可能会坚持参数检查但是……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读