2016-01-30 74 views
-1

我需要张贴uploades文件和模型,我使用MVC中的视图这样的代码:MVC帖子上传的文件和模型控制器

function GuardarDocumento() { 
var fileUpload; 
var tipoDoc; 
if (currentTabTitle == "#tab-AT") { 
    fileUpload = $("#inputFileAT").get(0); 
    tipoDoc = 'A'; 
} 

var files = fileUpload.files; 

var data = new FormData(); 
for (var i = 0; i < files.length; i++) { 
    data.append(files[i].name, files[i]); 
} 

var documento = { 
    Id_emd: 0, 
    Id_emm: { 
     Id_emm: id, 
     Tipo: tipo, 
    }, 
    Tipo_emd: tipoDoc, 
    Fecha_emd: $("#txtFechaDocAT").val(), 
    Nombre_emd: $("#txtNombreDocAT").val(), 
} 

$.ajax({ 
    url: "/Empleado/GuardarDocumento/" + JSON.stringify(documento), 
    type: "POST", 
    data: data, 
    contentType: false, 
    processData: false, 
    success: function (data) { 
     if (data.success) { 
      alert("Documento Guardado con Éxito."); 
      Cancelar(); 
     } 
     else { 
      alert(data.message); 
     } 
    }, 
    error: function (xhr, status, error) { 
     var err = eval("(" + xhr.responseText + ")"); 
     alert(err.Message); 
    } 
}); 

}

而控制器代码:

[HttpPost] 
    public ActionResult GuardarDocumento(clsDocumentoEmpleadoModel documento) 
    { 
     try 
     { 
      if (Request.Files.Count > 0) 
      { 
       clsEmpleadoBLL bll = new clsEmpleadoBLL(); 
       bll.PostedFile = Request.Files[0]; 
       documento.Archivo_emd = Request.Files[0].FileName; 
       bll.AddDocument(documento); 
      } 
      else 
      { 
       return Json(new { success = false, message = "No ha seleccionado ningún archivo." }); 
      } 
     } 
     catch (Exception ex) 
     { 
      GENException.Write(ex, "EmpleadoController.GuardarDocumento"); 
      return Json(new { success = false, message = string.Format("Error: {0}", ex.Message) }); 
     } 
     return Json(new { success = true, message = "Documento Guardado Correctamente." }); 
    } 

它不起作用,请求不好。如果我把网址:“/ Empleado/GuardarDocumento /”+ documento,我进入控制器代码,但模型为空。

出了什么问题?我正在向控制器发送上传的文件和模型,我该怎么做?

回答

0

您发送给控制器操作的类型必须与操作期望的类型匹配。您发送的是FormData,而您期待clsDocumentoEmpleadoModel

+0

好的,但我怎么能发送模型和上传文件到控制器在一个职位ajax调用? – DanielVorph

+0

动作类型需要与您发送的内容相匹配。如果您希望自己的操作支持模型和上传文件,那么您需要更改模型或在操作中接受两个参数。一个用于模型,另一个用于上传的文件。并使用ajax调用的'data'属性传递它们。 – mariocatch

+0

我用HttpPostedFileBase类型添加一个属性到我的模型中,在ajax调用中我分配了这个属性File:files [0],但是在控制器中这个属性总是为null其他属性具有正确的值,为什么是null? – DanielVorph