有没有办法让发布的文件(<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/