-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,我進入控制器代碼,但模型爲空。
出了什麼問題?我正在向控制器發送上傳的文件和模型,我該怎麼做?
好的,但我怎麼能發送模型和上傳文件到控制器在一個職位ajax調用? – DanielVorph
動作類型需要與您發送的內容相匹配。如果您希望自己的操作支持模型和上傳文件,那麼您需要更改模型或在操作中接受兩個參數。一個用於模型,另一個用於上傳的文件。並使用ajax調用的'data'屬性傳遞它們。 – mariocatch
我用HttpPostedFileBase類型添加一個屬性到我的模型中,在ajax調用中我分配了這個屬性File:files [0],但是在控制器中這個屬性總是爲null其他屬性具有正確的值,爲什麼是null? – DanielVorph