2017-06-15 54 views
-1

我需要传递多个文件使用ajax.form(异步)。ASP.NET MVC传递文件与ajax.form

我的表格:

@using (Html.BeginForm("EmployeeSkills", "Employee", FormMethod.Post, new {id= "UpdateForm", enctype = "multipart/form-data" })) 

我输入:

@Html.TextBoxFor(m => m.EmployeeSkillList[itemP].fileUpload, new { @class = "AddFileClass", type = "file", style = "width:90%", multiple = "multiple", id="uploadInputId"+itemP }) 

我的模型:

public class EmployeeSkillsModel 
{ 
    public int EmployeeSkillId { get; set; } 

    public int EmployeeId { get; set; } 

    [Required(ErrorMessageResourceType = typeof(Localization), ErrorMessageResourceName = "error_skill_category_required")] 
    [Display(Name = "category", ResourceType = typeof(Localization))] 
    public string Category { get; set; } 

    [Required(ErrorMessageResourceType = typeof(Localization), ErrorMessageResourceName = "error_skill_description_required")] 
    [Display(Name = "employee_skill", ResourceType = typeof(Localization))] 
    public string Name { get; set; } 

    [Required(ErrorMessageResourceType = typeof(Localization), ErrorMessageResourceName = "error_skill_level_required")] 
    [Display(Name = "skill_knowledge_level", ResourceType = typeof(Localization))] 
    public string KnowledgeLevel { get; set; } 

    [Display(Name = "additional_info", ResourceType = typeof(Localization))] 
    public string AdditionalInfo { get; set; } 

    [Display(Name = "attach_document", ResourceType = typeof(Localization))] 
    public List<string> UploadedFileNames{ get; set; } 

    [DataType(DataType.Upload)] 
    [Display(Name = "attach_document", ResourceType = typeof(Localization))] 
    public List<HttpPostedFileBase> fileUpload { get; set; } 

} 

但是在我EmployeeSkills方法fileUpload属性为null。我知道我可以移动到Html.BeginForm但希望保持异步的更新。

回答

1

那么,你还没有发布你的AJAX代码,这使它很难帮助你。但是,通常,通过AJAX上传文件需要以特定的方式进行处理。序列化表单以通过AJAX发布的传统方法不适用于文件上传。相反,您必须使用FormData,这是HTML5中的新功能。这也意味着通过AJAX进行文件上传只能在支持FormData的浏览器中使用,目前除了IE 9以外,它几乎都是其中的一切。如果您需要支持任何较低版本的IE,则必须使用不同的方法,包括Flash或Java小程序。

假设你可以放心地忽略IE的这些版本,它是那样简单:

$('#MyForm').on('submit', function (e) { 
    e.preventDefault(); 
    var formData = new FormData(this); // `this` is the form instance 
    $.ajax({ 
     url: '/path/to/handler', 
     type: 'POST', 
     data: formData, 
     processData: false, 
     contentType: 'multipart/form-data', 
     success: function (data, textStatus, jqXHR) { 
      // do something on success 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      // do something on error 
     } 
    }); 
});