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-mvc – 是否有官方的ASP.NET MVC参考/示例应用程序
- asp.net-mvc – 如何在本地化的文本中嵌入链接
- asp.net-mvc – 在路由路径中公开属于MVC应用程序中的区域的
- asp.net-mvc – 如何将MVC 3项目更新为jQuery 1.6?
- asp.net-web-api – ASP.NET Web API:如何在Web API控制器
- jQuery validate 根据 asp.net MVC的验证提取简单快捷的验证
- asp.net – 对于在Azure部署的Web.config中存储密码的正确程
- asp.net-mvc-3 – 什么是MVC 3中的ModelState类?
- 身份验证 – 如何仅为ASP.NET 5中的受保护操作添加令牌验证
- asp.net – Web窗体中的.NET MVC FileResult等价物
- asp.net – ASP .net当前物理位置
- asp.net-mvc-4 – 无法让ASP.NET 4 Web API返回状
- asp.net-web-api – 从ExceptionLogger引用操作参
- asp.net Gridview,1记录跨度两行
- asp.net-mvc – ASP.NET MVC路由Maproute参数
- asp.net-mvc – MVC区域 – 非区域路线解析为区域
- asp.net-core – 在ASP.net Core中使用BeginColl
- asp.net-mvc-3 – 如何将int数组传递给RouteValu
- asp.net-mvc – asp.net mvc中的动态子域
- asp.net-mvc – 运行时错误没有为扩展名’.cshtm
