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

前端 未结 7 2090
误落风尘
误落风尘 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:38

    Try to create a model binder as in below

    public class MyModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {                
                var request = controllerContext.HttpContext.Request;
    
                return new MyModel
                {
                    MyEmpls = request[] ?? new Employees[0],
                    Id = request["Id"] ?? "",
                    OrgName = request["OrgName"] ?? ""
    
                };
            }
            catch 
            {
                //do required exception handling
            }
        }
    }
    

    In Application_Start register the model binder

    ModelBinders.Binders.Add(typeof(MyModel), new MyModelBinder())
    

    And modify the controller as

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

提交回复
热议问题