Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-mvc

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 ?

like image 571
user49126 Avatar asked Jan 03 '12 09:01

user49126


2 Answers

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. E.g.:

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...

like image 158
Matthew Abbott Avatar answered Nov 10 '22 16:11

Matthew Abbott


simply do it yourself

public ActionResult GetGridData(IList<string> coll)
{
    if(coll == null)
        coll = new List<String>();
    //Do other stuff
}
like image 1
Maheep Avatar answered Nov 10 '22 15:11

Maheep