1

I want to save multiple images at once using asp.net mvc4. At view side I have 5 browse button and I'm successf. getting those file at the controller side as parameter at post action IEnumerable<HttpPostedFileBase> postedPhotos.

  1. I want to know if postedPhotos[0] was sent, if so save it to the db.
  2. iterate trough remaining postedPhotos collection and take further action only to those which actually contains photo (user can send only one or two image instead of five)

so I tried with

if(postedPhotos.First() != null)
foreach(var photo in postedPhotos.Where(x=>x.ContentLength>0))
{....}

but this doesn't work since I'm touching postedPhoto null value and I'm getting exception

Object reference not set to an instance of an object.

ofcourse everything works if I send all five photos but I'm interesting how to handle this situation.

THanks

4

1 回答 1

2

尝试:

if(postedPhotos != null && postedPhotos.FirsOrDefault() != null) 

First()和之间的区别在于,如果集合中没有项目而只返回 null FirstOrDefault()First()则会引发异常。FirstOrDefault()

您也可以使用Any()代替FirstOrDefault() != null.

关于你的第二个问题:我不太清楚你想要什么。仅当foreach集合中有任何项目时,循环才会迭代。

于 2013-10-01T21:26:01.180 回答