ASP.NET MVC - Binds an empty collection when a parameter is null

I have several methods of actions with parameters like IList.

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

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

Is there a way to get an empty collection and not an empty application?

+4
source share
2 answers

Well, you can do this:

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

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

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

And connected as:

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

I would probably stick with argument checking though ...

+5
source

just do it yourself

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

Source: https://habr.com/ru/post/1389045/


All Articles