微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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"

也相关:

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());

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

原文地址:https://www.jb51.cc/aspnet/247285.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐