2010-01-20 64 views
1

我不能让asp.net mvc 1.0为我绑定HttpPostedFileBase。无法让HttpPostedFileBase在Asp.Net MVC 1.0中正确绑定

这是我的EditModel类。

public class PageFileEditModel 
{ 
    public HttpPostedFileBase File { get; set; } 
    public string Category { get; set; } 
} 

这是我的编辑方法标题。

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Edit(int id, FormCollection formCollection, PageFileEditModel[] pageFiles) 

,这是我的HTML

<input type="file" name="pageFiles[0].File" /> 
<input type="text" name="pageFiles[0].Category" /> 
<input type="file" name="pageFiles[1].File" /> 
<input type="text" name="pageFiles[1].Category" /> 

分类正确绑定,但文件总是空。

我已验证文件确实在Request.Files

HttpPostedFileBaseModelBinder默认情况下添加这样也弄不清是怎么回事错..

+1

唯一能想到的就是我的头顶:表单的“enctype”属性是否设置为“multipart/form-data”? – 2010-01-20 14:04:56

+0

是的,我已经验证这些文件确实在Request.Files中。 – 2010-01-20 14:30:46

回答

1

有在MVC 1,其中HttpPostedFileBase如果他们是你的模型类型,而不是你的操作方法性能参数的对象是未绑定的错误(固定在MVC 2 RC)。解决方法对于MVC 1:

<input type="file" name="theFile[0]" /> 
<input type="hidden" name="theFile[0].exists" value="true" /> 
<input type="file" name="theFile[1]" /> 
<input type="hidden" name="theFile[1].exists" value="true" /> 

也就是说,对于每一个文件上传元素 .exists隐藏输入元素。这将导致DefaultModelBinder的短路逻辑无法启动,它应该正确绑定HPFB属性。

+0

bam!如下所示: 2010-01-20 21:34:30

1

这是一种规范。

Scott Hanselman's Computer Zen - ASP.NET MVC Beta released - Coolness Ensues

这是V1 RTW基础模型粘合剂样本代码。

1.制作自定义模型联编程序。

using System.Web.Mvc; 

namespace Web 
{ 
    public class HttpPostedFileBaseModelBinder : IModelBinder 
    { 
    public object BindModel(ControllerContext controllerContext, 
          ModelBindingContext bindingContext) 
    { 
     var bind = new PostedFileModel(); 
     var bindKey = (string.IsNullOrEmpty(bindingContext.ModelName) ? 
     "" : bindingContext.ModelName + ".") + "PostedFile"; 
     bind.PostedFile = controllerContext.HttpContext.Request.Files[bindKey]; 

     return bind; 
    } 
    } 
} 

2.创建模型类。

using System.Web; 

namespace Web 
{ 
    public class PostedFileModel 
    { 
    public HttpPostedFileBase PostedFile { get; set; } 
    } 
} 

3. global.asax.cs中的条目模型联编程序。

protected void Application_Start() 
{ 
    RegisterRoutes(RouteTable.Routes); 
    ModelBinders.Binders[typeof(PostedFileModel)] = 
       new HttpPostedFileBaseModelBinder(); 
} 
+0

已经在MVC 1.0中实现RTM – 2010-01-20 16:51:40

+0

我认为在复杂类型上解绑定HttpPostedFileBase。 – takepara 2010-01-21 01:57:29