开发者

How to bind uploaded files to IEnumerable<HttpPostedFileBase> property

开发者 https://www.devze.com 2022-12-20 11:45 出处:网络
This the html form: <input id=\"picture1\" name=\"Input_Pictures\" type=\"file\" value=\"\" /> <input id=\"picture2\" name=\"Input_Pictures\" type=\"file\" value=\"\" />

This the html form:

<input id="picture1" name="Input_Pictures" type="file" value="" />
<input id="picture2" name="Input_Pictures" type="file" value="" />
<input id="picture3" name="Input_Pictures" type="file" value="" />

I also tried:

<input id="picture1" name="Input_Pictures[]" type="file" value="" />
<input id="picture2" name="Input_Pictures[]" type="file" value="" />
<input id="picture3" name="Input_Pictures[]" type="file" value="" />

and also too:

<input id="picture1" name="Input_Pictures[0]" type="file" value="" />
<input id="picture2" name="Input_Pictures[1]" type="file" value="" />
<input id="picture3" name="Input_Pictures[2]" type="file" value="" />

This is my view model:

public class PicturesInputViewModel
{
     public IEnumerable<HttpPostedFileBase> Pictures { get; set; }
}

And this is the submit action:

[HttpPost]
public ActionResult Submit(PicturesInputViewModel input)      
{

I can see the files in Request.Files collection, but Pictures is always null.

How can I solve this binding problem?


For the mean time I using this code succe开发者_运维知识库ssfully:

 var pics = new List<HttpPostedFileBase>();
 foreach (string name in Request.Files)
 {
     var file = Request.Files[name];
         if (file.ContentLength > 0)
             pics.Add(file);        
 }
 input.Pictures = pics;


Try to give your controls different names: Picture[1], Picture[2], .. , Picture[n]. Binder cannot decide that picture2 must be in Pictures collection.

Sorry, MVC doesn't have binder for collections of files. You can use FileCollectionModelBinder from MvcFutures project. All you have to do is to reference MVCFutures assembly and add additional model binder (in global.asax.cs or elsewhere):

FileCollectionModelBinder.RegisterBinder(ModelBinders.Binders); 


Check out this post Having troubles calling a Controller Post Method…

This might give you a clue as to how to fix your issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消