c# - string[] 数组返回“对象引用未设置为对象实例”的错误。
问题描述
使用数组参数向控制器提交 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()
:
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...
}
推荐阅读
- javascript - 选择选择选项时将数据加载到 div
- python - Pandas 中的嵌套迭代
- javascript - 浏览器是否提供面向对象的 *element* 实例或分层树结构或两者兼而有之?
- javascript - 如何使用ajax每秒使用表单数据
- angular - Angular 6x CLI:如何在开发控制台中抑制 SCSS 编译警告
- c# - 如何比较预制件和游戏对象?
- regex - 如果之前的句子中有特定的单词,则匹配一个单词
- sapui5 - 使用 typescript 进行开发和使用 Component-preload.js 进行生产调试
- flutter - 强制 TabController 创建所有选项卡 Flutter
- ios - Parse - 查询数组指针中的值