Why does the ASP.Net MVC model binder bind an empty JSON array to null?

前端 未结 7 2097
误落风尘
误落风尘 2020-12-15 15:52

Here is my model class:

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

7条回答
  •  情话喂你
    2020-12-15 16:50

    You're getting a null value as this is the default value for a reference type in C#. In order to get an empty array you will need to initialise the array in your model using a constructor. However as you will need to define the size of the array when it's initialized it might be better using another type of collection such as a List:

    public class MyModel
    {
        public List MyEmpls{get;set;}
        public int Id{get;set;}
        public OrgName{get;set;}
    
        public MyModel() 
        {
             MyEmpls = new List();
        }
    }
    

    You will then get an empty list when an empty array is passed from the json.

    If you really have to use an array just initialise it with a size:

    public class MyModel
    {
        public Employees[] MyEmpls{get;set;}
        public int Id{get;set;}
        public OrgName{get;set;}
    
        public MyModel() 
        {
             MyEmpls = new Employees[/*enter size of array in here*/];
        }
    }
    

提交回复
热议问题