【问题标题】:How to bind uploaded files to IEnumerable<HttpPostedFileBase> property如何将上传的文件绑定到 IEnumerable<HttpPostedFileBase> 属性
【发布时间】:2010-02-19 04:14:16
【问题描述】:

这是html表单:

<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="" />

我也试过了:

<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="" />

还有:

<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="" />

这是我的视图模型:

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

这是提交操作:

[HttpPost]
public ActionResult Submit(PicturesInputViewModel input)      
{

可以查看Request.Files 集合中的文件,但Pictures 始终为空。

如何解决这个绑定问题?


目前我成功使用了这段代码:

 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;

【问题讨论】:

    标签: .net asp.net-mvc viewmodel


    【解决方案1】:

    尝试为您的控件指定不同的名称: Picture[1], Picture[2], .. , Picture[n]。 Binder 无法确定图片 2 必须在图片集合中。

    抱歉,MVC 没有用于文件集合的活页夹。 您可以使用来自MvcFutures 项目的 FileCollectionModelBinder。 您所要做的就是引用 MVCFutures 程序集并添加额外的模型绑定器(在 global.asax.cs 或其他地方):

    FileCollectionModelBinder.RegisterBinder(ModelBinders.Binders); 
    

    【讨论】:

    • 对不起,我指的是图片[n],而不是图片[n]
    【解决方案2】:

    查看这篇帖子Having troubles calling a Controller Post Method…

    这可能会为您提供有关如何解决问题的线索。

    【讨论】:

    • 这并不是绑定问题的线索。
    猜你喜欢
    • 1970-01-01
    • 2014-09-01
    • 2013-07-20
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多