简体   繁体   中英

ASP.NET MVC - bind empty collection when parameter is null

I've couple of action methods with parameters of IList type.

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

The default behavior is when no data are passed to action method the parameter is null.

Is there any way to get an empty collection rather then null application wide ?

Well, you could either do this:

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

Or you would need to implement a ModelBinder that will create an empty list instead of returning null. Eg:

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

And wired up as:

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

I'd probably stick with the argument check though...

simply do it yourself

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM