asp.net-mvc – 如何将名为“file []”的已发布数据绑定到MVC模
我使用
Redactor作为HTML编辑器,它有一个
component for uploading images and files.
Redactor负责客户端位,我需要提供服务器端上传功能. 如果我在控制器中使用Request.Files,我没有问题让上传工作. 但我想将发布的文件绑定到模型,我似乎无法做到这一点,因为它们发送的参数是files [] – 名称中带有方括号. 我的问题: 是否可以将发布的“file []”绑定到MVC模型?这是一个无效的属性名称,仅使用文件不起作用. 此文件输入如下所示.我可以指定文件以外的名称,但Redactor会将[]添加到末尾,而不管名称如何. <input type="file" name="file" multiple="multiple" style="display: none;"> 我试图绑定到这样的属性: public HttpPostedFileBase[] File { get; set; } 当我看到上传发生时,我在请求中看到了这一点(我认为redactor可能会在幕后添加方括号): Content-Disposition: form-data; name="file[]"; filename="my-image.jpg" 也相关:
解决方法
您应该创建自定义模型绑定器以将上载的文件绑定到一个属性.
首先使用HttpPostedFileBase []属性创建一个模型 public class RactorModel { public HttpPostedFileBase[] Files { get; set; } } 然后实现DefaultModelBinder并覆盖BindProperty public class RactorModelBinder : DefaultModelBinder { protected override void BindProperty(ControllerContext controllerContext,ModelBindingContext bindingContext,PropertyDescriptor propertyDescriptor) { int len = controllerContext.HttpContext.Request.Files.AllKeys.Length; if (len > 0) { if (propertyDescriptor.PropertyType == typeof(HttpPostedFileBase[])) { string formName = string.Format("{0}[]",propertyDescriptor.Name); HttpPostedFileBase[] files = new HttpPostedFileBase[len]; for (int i = 0; i < len; i++) { files[i] = controllerContext.HttpContext.Request.Files[i]; } propertyDescriptor.SetValue(bindingContext.Model,files); return; } } base.BindProperty(controllerContext,bindingContext,propertyDescriptor); } } 您还应该将binder提供程序添加到项目中,然后在global.asax中注册它 public class RactorModenBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(Type modelType) { if (modelType == typeof(RactorModel)) { return new RactorModelBinder(); } return null; } } ... ModelBinderProviders.BinderProviders.Insert(0,new RactorModenBinderProvider()); 这不是一般解决方案,但我想你明白了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- ASP.NET Core&EntityFramework核心:左(外)加
- 如何以编程方式设置ASP.NET ReportViewer控件的数
- asp.net-mvc – 我可以从动作过滤器返回动作结果
- asp.net-core – 将应用程序root路由到/ swagger
- ASP.net MVC5中的asp.net-mvc – CORS
- asp.net-mvc-3 – 为什么我的IgnoreRoute不起作用
- asp.net-mvc – MVC打开pdf文件
- 从ASP.NET应用程序直接将文件上传到Amazon S3
- asp.net-mvc-3 – ASP.NET MVC 3 Razor查看oncli
- asp.net – 什么设置的User.Identity.Name和User