Passing empty js array to controller gives null

2019-02-05 12:44发布

Here is my model which is a WCF Proxy class

public class MyModel
{
    public Employees[] MyEmpls{get;set;}
    public int Id{get;set;}
    public OrgName{get;set;}
}

Passing a below json structure object with MyEmpls as empty array to MVC controller.

["Id":12, "MyEmpls":[], "OrgName":"Kekran Mcran"]

Controller

[HttpPost]
public ActionResult SaveOrg(MyModel model)
{
  //model.MyEmpls is null here
}

I am expecting mode.MyEmpls as empty c# array and not null. Could some one help me here? Do we need to write a custom model binder for this?

7条回答
太酷不给撩
2楼-- · 2019-02-05 13:43

you can define a setter that checks if the value is null

public class MyModel
{
    private _myEmpls{get;set;}
    public Employees[] MyEmpls{
     get{return _myEmpls;}
     set{_myEmpls=(value==null?new List<Employees>():value);}
    }

    public int Id{get;set;}
    public OrgName{get;set;}
}
查看更多
登录 后发表回答