代码之家  ›  专栏  ›  技术社区  ›  Carl Hörberg

无法在ASP.NET MVC 1.0中使httpPostedFileBase正确绑定

  •  1
  • Carl Hörberg  · 技术社区  · 15 年前

    我不能让ASP.NET MVC 1.0为我绑定httpPostedFileBase。

    这是我的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 是默认添加的,因此无法确定发生了什么问题。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Levi    15 年前

    MVC 1中有一个bug(在MVC 2 RC中修复了),如果httpPostedFileBase对象是模型类型上的属性,而不是操作方法的参数,则不会绑定它们。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" />
    

    也就是说,对于每个文件上传元素 FOO公司 有一个 。存在隐藏的输入元素。这将导致DefaultModelBinder的短路逻辑无法启动,并且它应该正确绑定hpfb属性。

        2
  •  1
  •   takepara    15 年前

    这是规范。

    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();
    }