以一种formsMVC4上传多个文件

我正在尝试在一个表单上上传多个图像

@using (Html.BeginForm("Create", "AdminRestaurants", FormMethod.Post, new { enctype = "multipart/form-data" })) { 

我正试图用这个处理控制器上的表单

 public ActionResult Create(IEnumerable files, RestaurantModel collection) { if (ViewData.ModelState.IsValid) { } } 

目前,控制器上的files签名中没有任何内容。 只使用一个文件时,这似乎很有效

 public ActionResult Create(HttpPostedFileBase file, EventsModel collection) 

有人能指出我允许使用一个提交表单上传多个文件的方向吗?

您的问题是表单创建了一个post请求,其中包含模型绑定器可以绑定的信息,因为命名约定不正确。

你看,你有4个文件字段,每个字段都有不同的名称,模型绑定器正确绑定它们你的控制器动作签名应如下所示:

 public ActionResult Create(HttpPostedFileBase mgmFile, HttpPostedFileBase logoFile, HttpPostedFileBase fohFile , HttpPostedFileBase bohFile) 

遵循MCV设计模式最好的选择是使用包含IEnumerable的ViewModel,然后为IEnumerable创建自定义编辑器模板

所以你可以这样使用它:

 Html.EditorFor(m=>Model.filesUploaded) 

你的控制器动作看起来像这样:

 public ActionResult Create(MyViewModel i_InputModel) { i_InputModel.filesUploade; //Use the files here to upload them. } 

其他选项包括:在文件输入字段上使用HTML5 multiple属性,如下所示:

  

和这样的控制器动作:

 public ActionResult Create(HttpPostedFileBase files) 

或使用多个文件字段,但在其名称中对其进行索引:

     

然后你可以使用像这样的控制器动作:

 public ActionResult Create(IEnumerable files) 

只有当您的文件输入具有索引名称(如files[0]files[1]files[2] ,… files[2] ,这才有效。

为了理解模型绑定到列表如何在asp.net mvc中工作,我建议你阅读这篇文章: 模型绑定到列表

您甚至不必使用模型绑定来获取文件。 在Action中使用Request.Files来获取它们。

 public ActionResult Create(EventsModel collection) { var files = Request.Files; // rest of the code... } 
    

在这里,我用简单的例子演示: http : //www.infinetsoft.com/Post/How-to-create-multiple-fileUpload-using-asp-net-MVC-4/1229#.V0J-yfl97IU