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

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

    [HttpPost]
    public ActionResult SaveOrg(MyModel model)
    {
        var serializer = new JavaScriptSerializer();
        var stream = System.Web.HttpContext.Current.Request.InputStream;
        var reader = new StreamReader(stream);
        stream.Position = 0;
        var json = reader.ReadToEnd();
        model= serializer.Deserialize(json);
        //model.MyEmpls is [] here
    }
    

    JavaScriptSerializer deserializes empty arrays properly. So you can ignore the passed-in model and rebuild it from the input request stream. Probably not the correct way, but if you only need to do it once it saves some effort. You'll need to reference System.Web.Extensions.

提交回复
热议问题