首页 > 解决方案 > 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];
            }
        }

    }

令人沮丧,因为我之前有这个工作。我没有改变任何会导致它现在这样做的东西。任何帮助将不胜感激。

标签: c#jqueryasp.net-mvcmodel-view-controller

解决方案


也许您需要在调用参数数组中的元素之前对其进行空检查.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...
}

推荐阅读