-9

这里我的代码是它显示你传递的参数是空的: -

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
     if (Seats.Count(x => x.IsSelected) == 0)
     {
            return "you didnt select any seats";
     }
     else
     {
           StringBuilder sb = new StringBuilder();
           sb.Append("you selected");
           foreach (Seat seat in Seats)
           {
               if (seat.IsSelected)
               {
                   sb.Append(seat.Name + " ,");
               }
            }
           sb.Remove(sb.ToString().LastIndexOf(","), 1);
           return sb.ToString();
     }   
}
4

2 回答 2

2

如果您在没有匹配数据/查询参数的情况下调用该方法,则座位将为空。您还需要检查,例如:

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
     if ((Seats == null) || !Seats.Any(s => s.IsSelected))
     {
            return "you didnt select any seats";
     }
     else
     {
           return "you selected " + string.Join(", ", Seats.Where(s => s.IsSelected).Select(s => s.Name));
     }   
}
于 2016-10-20T08:22:29.273 回答
2

出现例外是因为——正如 Lucero 已经提到的——Seatsnull。与通常的方法相比,您不会在NullReferenceException这里得到 a ,因为Count它是一种扩展方法:

public static int Count(this IEnumerable<T> source)
{
    if (source == null) throw new ArgumentNullException("source");
}

因此,如您所见,该方法会抛出 anArgumentNullException而不是NullReferenceExceptionif sourceis null

顺便说一句,不要用于Count检查您的集合是否有项目,Any而是使用它,因为它不会枚举完整的集合并在找到第一个匹配条件时返回。

编辑:如果您要使用另一种方法,这是一种普通的实例方法,您会得到一个 NRE:

Seats.DoSomething(); // throws NRE when Seats = null

所以检查参数是否null在使用它之前:

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
    if (Seats == null || !Seats.Any(x=> x.IsSelected))
        return "you didnt select any seats";
}
于 2016-10-20T08:28:14.777 回答