将空的js数组传递给控制器​​会给出null

这是我的模型,它是一个WCF代理类

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

将具有MyEmpls as empty array的下面的json结构对象MyEmpls as empty array传递给MVC控制器。

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

调节器

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

我期待mode.MyEmpls为空c#数组而不是null。 有人可以帮助我吗? 我们需要为此编写自定义模型绑定器吗?

我认为其他一些答案已经错过了问题的含义:为什么默认的MVC模型绑定器将空的Json数组绑定为null而不是空的C#数组?

好吧,我不能告诉你为什么他们这样做,但我可以告诉你它发生在哪里。 可以在CodePlex上找到MVC的源代码: http : //aspnetwebstack.codeplex.com/SourceControl/latest 。 您正在寻找的文件是ValueProviderResult.cs ,您可以在其中看到:

  private static object UnwrapPossibleArrayType(CultureInfo culture, object value, Type destinationType) { if (value == null || destinationType.IsInstanceOfType(value)) { return value; } // array conversion results in four cases, as below Array valueAsArray = value as Array; if (destinationType.IsArray) { Type destinationElementType = destinationType.GetElementType(); if (valueAsArray != null) { // case 1: both destination + source type are arrays, so convert each element IList converted = Array.CreateInstance(destinationElementType, valueAsArray.Length); for (int i = 0; i < valueAsArray.Length; i++) { converted[i] = ConvertSimpleType(culture, valueAsArray.GetValue(i), destinationElementType); } return converted; } else { // case 2: destination type is array but source is single element, so wrap element in array + convert object element = ConvertSimpleType(culture, value, destinationElementType); IList converted = Array.CreateInstance(destinationElementType, 1); converted[0] = element; return converted; } } else if (valueAsArray != null) { // case 3: destination type is single element but source is array, so extract first element + convert if (valueAsArray.Length > 0) { value = valueAsArray.GetValue(0); return ConvertSimpleType(culture, value, destinationType); } else { // case 3(a): source is empty array, so can't perform conversion return null; } } // case 4: both destination + source type are single elements, so convert return ConvertSimpleType(culture, value, destinationType); } } 

有趣的部分是“案例3”:

 else { // case 3(a): source is empty array, so can't perform conversion return null; } 

您可以通过在构造函数中初始化模型上的数组来回避此问题。 在我快速阅读源代码时,我无法告诉你为什么他们不能返回一个空数组或为什么他们决定不这样做,但它应该有趣的阅读。

您将获得一个空值,因为这是C#中引用类型的默认值。 为了获得一个空数组,您需要使用构造函数初始化模型中的数组。 但是,由于您需要在初始化时定义数组的大小,因此使用其他类型的集合(例如List可能会更好:

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

然后,当从json传递空数组时,您将获得一个空列表。

如果你真的必须使用一个数组,只需用一个大小初始化它:

 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]; } } 

如果你将model.MyEmpls变为null,那么你可以在服务器端创建一个条件来停止引发exception,如:

 if(model.MyEmpls !=null){ ... } 

而且你得到它是因为你的MyEmpls是一个自定义类数组而你只是发送[]。

希望这对你有所帮助。

尝试创建模型绑定器,如下所示

 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 } } } 

在Application_Start中注册模型绑定器

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

并将控制器修改为

 [HttpPost] public ActionResult SaveOrg([ModelBinder(typeof(MyModelBinder))] MyModel model) { //model.MyEmpls is null here } 
 [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正确地反序列化空数组。 因此,您可以忽略传入的模型并从输入请求流重建它。 可能不是正确的方法,但如果你只需要做一次省下一些努力。 您需要引用System.Web.Extensions。

您可以定义一个setter来检查该值是否为null

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

C#数组初始化的默认行为是null而不是空数组

因此,如果发送一个空数组,则不会启动空数组,但是您将触发默认初始化为null

请参阅以下链接http://www.dotnetperls.com/null-array