繁体   English   中英

string[] 数组返回“对象引用未设置为 object 的实例”的错误。

[英]string[] array is returning error of “Object reference not set to an instance of an object.”

使用数组参数向 controller 提交 POST ajax 调用。

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

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

这是 controller:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM