Reputation: 4460
I'm trying make multiple file upload and to do this I am using ICollection<HttpPostedFileBase>
. I choosed to use ICollection
instead of IEnumerable
because using ICollection
I can use the function Count
to check size of ICollection
. It works very well, the problem is when I try check the size it always has one value even it is empty, even I don't select any file it has one value, and I don't know why it's happens.
Why ICollection always has one value even I don't choose a file ? How could I fix this ?
Model
public ICollection<HttpPostedFileBase> imagens { get; set; }
HTML
<div class="form-group">
<label for="@Html.IdFor(model => model.imagens)" class="col-md-12 control-label">Imagens (Max.10) </label>
<div class="col-md-10">
@Html.TextBoxFor(model => model.imagens, new{
Class = "form-control",
placeholder = "Escolha as imagens",
multiple = "multiple",
type = "file"
})
@Html.ValidationMessageFor(model => model.imagens)
</div>
</div>
Controller
//check if ICollection is empty. It still doesn't works.
if (model.imagens.Count == 0){
jsonResposta.Add("status", "0");
jsonResposta.Add("msg", "Add at least one picture");
return Json(jsonResposta);
}
Upvotes: 2
Views: 234
Reputation: 218722
This has nothing to do with your collection type (ICollection
). The browser (chrome is what i checked) is always sending form data item of application/octet-stream
type even though you do not select any file. This happens for single file selector and multiple file selector. I believe it is the Model binder which is handling it properly for the single file, but not handling it properly when your property type is HttpPostedFileBase collection.
Your best solution now is to filter it out your self.
[HttpPost]
public ActionResult Index(YourViewModel model)
{
var validFiles = model.imagens.Where(g=>g!=null).ToList();
//use validFiles from now onwards
// to do : Return something
}
Upvotes: 1