加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何将名为“file []”的已发布数据绑定到MVC模

发布时间:2020-12-16 04:07:39 所属栏目:asp.Net 来源:网络整理
导读:我使用 Redactor作为HTML编辑器,它有一个 component for uploading images and files. Redactor负责客户端位,我需要提供服务器端上传功能. 如果我在控制器中使用Request.Files,我没有问题让上传工作. 但我想将发布的文件绑定到模型,我似乎无法做到这一点,因
我使用 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"

也相关:

Redactor always sends the uploading request with content-type as multipart/form-data. So you don’t need to add this enctype anywhere

解决方法

您应该创建自定义模型绑定器以将上载的文件绑定到一个属性.
首先使用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());

这不是一般解决方案,但我想你明白了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读