asp.net-mvc - 当参数为模型时,ASP.NET MVC 发布文件模型绑定(bind)

标签 asp.net-mvc modelbinders defaultmodelbinder httppostedfilebase

有没有办法让发布的文件(<input type="file" />)参与 ASP.NET MVC 中的模型绑定(bind) 无需手动查看自定义模型绑定(bind)器中的请求上下文,也无需创建仅将发布的文件作为输入的单独操作方法?

我原以为这会起作用:

class MyModel {
  public HttpPostedFileBase MyFile { get; set; }
  public int? OtherProperty { get; set; }
}

<form enctype="multipart/form-data">
  <input type="file" name="MyFile" />
  <input type="text" name="OtherProperty" />
</form>

public ActionResult Create(MyModel myModel) { ... } 

但鉴于上述情况, MyFile甚至不是绑定(bind)上下文中值提供者值的一部分。 ( OtherProperty 是,当然。)但如果我这样做,它会起作用:
public ActionResult Create(HttpPostedFileBase postedFile, ...) { ... } 

那么,为什么当参数是模型时没有发生绑定(bind),我怎样才能让它工作呢?我使用自定义模型绑定(bind)器没有问题,但是如何在自定义模型绑定(bind)器中执行此操作而不查看 Request.Files["MyFile"] ?

为了一致性、清晰性和可测试性,我希望我的代码能够自动绑定(bind)模型上的所有属性,包括绑定(bind)到已发布文件的属性,而无需手动检查请求上下文。我目前正在使用 the approach Scott Hanselman wrote about 测试模型绑定(bind).

还是我以错误的方式解决这个问题?你会如何解决这个问题?或者由于 Request.Form 和 Request.Files 之间的分离历史,这是设计上不可能的?

最佳答案

你看过this post他从 the one you linked to 链接到(通过 another one ...)?

如果没有,它看起来很简单。这是他使用的模型粘合剂:

public class HttpPostedFileBaseModelBinder : IModelBinder {
    public ModelBinderResult BindModel(ModelBindingContext bindingContext) {
        HttpPostedFileBase theFile =
            bindingContext.HttpContext.Request.Files[bindingContext.ModelName];
        return new ModelBinderResult(theFile);
    }
}

他在 Global.asax.cs 中注册。如下:
ModelBinders.Binders[typeof(HttpPostedFileBase)] = 
    new HttpPostedFileBaseModelBinder();

并以如下形式发布:
<form action="/File/UploadAFile" enctype="multipart/form-data" method="post">
    Choose file: <input type="file" name="theFile" />
    <input type="submit" />
</form>

所有代码都直接从博客文章中复制...

关于asp.net-mvc - 当参数为模型时,ASP.NET MVC 发布文件模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/960687/

相关文章:

asp.net-mvc - 复杂类型嵌套对象的绑定(bind)属性包含和排除属性

c# - 默认模型绑定(bind)器不绑定(bind) IEnumerable 中的 Nullable 类型

c# - 如何在使用 AddNewtonsoftJson 时在 asp net core 3.1 mvc 中通过 DI(服务集合)检索 json 序列化程序设置

.net - 我如何知道一个项目是哪个版本的asp.net mvc?

ASP.Net MVC优雅的UI和ModelBinder授权

asp.net-mvc-3 - MVC3 Razor 模型绑定(bind)器和继承的集合

c# - 模型 Binder 问题

asp.net-mvc - DefaultModelBinder 嵌套级别+其他绑定(bind)器的问题

asp.net-mvc - 将参数映射到模型时使用哪种语言?

JQUERY ajax 将值从 MVC View 传递到 Controller