gpt4 book ai didi

c# - 为什么 ASP.Net MVC 模型绑定(bind)器将空 JSON 数组绑定(bind)到 null?

转载 作者:IT老高 更新时间:2023-10-28 12:48:42 25 4
gpt4 key购买 nike

这是我的模型类:

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

将以下带有 MyEmpls 作为空数组 的 JSON 结构对象传递给 MVC Controller 。

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

Controller

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

我希望 mode.MyEmpls 是一个空的 c# 数组,而不是 null。实现空数组是否需要自定义模型绑定(bind)器?

最佳答案

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

嗯,我不能告诉你他们为什么这样做,但我可以告诉你它发生在哪里。 MVC 的源代码可以在 CodePlex 上找到: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# - 为什么 ASP.Net MVC 模型绑定(bind)器将空 JSON 数组绑定(bind)到 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com