字符串[] 数组返回错误 "Object reference not set to an instance of an object."



向带有数组参数的控制器提交POST ajax调用。

我有一个参数数组,
我有一一个静态数组,我用它来检查参数数组
我使用.Except方法创建了第三个数组,以创建除参数值之外的所有数组。

POST ajax调用工作正常。我可以返回并查看我发送给它的值。这就是我使用快速TempData所做的。所以,我知道参数不是空的。

这是控制器:

[HttpPost]
public ActionResult MyAction(string[] subLineNames)
{
//Static array to check against parameter
string[] sublineArray = new string[] { "BI/PD", "Hired", "Non-Owned", "PIP", "Addtl-PIP", "Medical Payments", "UM PD", "UM CSL", "UIM CSL", "Terrorism" };
//Create new array for all minus the values in the parameter
/* The error happens here. The .Trim is causing some issue I can't see.  */
/* I know that jquery ajax call is sending a bunch of white space, so I use trim to get rid of the white space characters. */
string[] DifferArray = sublineArray.Except(subLineNames.Select(m => m.Trim())).ToArray();
//Test to ensure the array parameter is not empty. (it works and brings back what I sent to it)
if (subLineNames != null)
{
for (int i = 0; i < subLinesNames.Length - 1; i++)
{
TempData["AA"] += subLineNames[i];
}
}
}

很沮丧,因为我之前有过这样的工作。我没有改变任何会导致它现在这样做的事情。如有任何帮助,我们将不胜感激。

在对参数数组中的元素调用.Trim()之前,可能需要对其进行null检查:

string[] DifferArray = sublineArray.Except(subLineNames.Where(m => !string.IsNullOrWhiteSpace(m)).Select(m => m.Trim())).ToArray();

更好的是,您可以存储对经过净化的参数数组的引用:

[HttpPost]
public ActionResult MyAction(string[] subLineNames)
{
if (subLineNames == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, $"You must provide {nameof(subLineNames)}.");
}
var sanitizedSubLineNames = subLineNames.Where(m => !string.IsNullOrWhiteSpace(m)).Select(m => m.Trim());
var sublineArray = new string[] { "BI/PD", "Hired", "Non-Owned", "PIP", "Addtl-PIP", "Medical Payments", "UM PD", "UM CSL", "UIM CSL", "Terrorism" };
var differArray = sublineArray.Except(sanitizedSubLineNames).ToArray();
// Do something...
}

相关内容

最新更新