【发布时间】:2016-12-15 10:57:08
【问题描述】:
首先感谢大家的帮助。我已经花了将近 7 个小时没有成功。
我正在使用 ASP.net MVC 5。我创建了一个控制器创建和一个视图(带有表单)。我的表单接收诸如姓名、姓氏、头衔等信息。我还想添加将存储在服务器上的文件。 我认为我已经正确地完成了表格
<form id="wizard-1" novalidate="novalidate" enctype="multipart/form-data">
...
<p> Date d'envoi :</p>
<label class="input margin-bottom-5">
<i class="icon-append fa fa-calendar"></i>
<input type="date" name="Date_envoie_OT" autocomplete="off" class="form-control">
</label>
...
<input type="file" name="file" id="file" />
<button type="button" class=" btn btn-primary">Enregistrer</button>
我也有ajax函数
var data = new FormData();
var files = $("#file").get(0).files;
if (files.length > 0) { data.append("HelpSectionImages", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var extension = $("#file").val().split('.').pop().toUpperCase();
if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
common.showNotification('warning', 'Imvalid image file format.', 'top', 'right');
return false;
}
var OT = $('#wizard-1').serialize();
$.ajax({
url: '@Url.Action("Create")',
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: '{"OT":"' + $('#wizard-1').serialize() + '","Id_agence":"' + $('#Id_agence').serialize() + '", "data":"' + data + '"}',
success: function (data) {
$.smallBox({
title: "Enregistrement validé",
content: "<i class='fa fa-clock-o'></i> <i>L'O.T. a pas enregistré (prévenez le pool en charge)</i>",
color: "#E82E13",
iconSmall: "fa fa-times bounce animated",
timeout: 7000
});
我的控制器
public JsonResult Create(Ordre_Travaux OT, int Id_agence, HttpPostedFileBase 数据)
{
if (ModelState.IsValid)
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
var fileName = Path.GetFileName(filebase.FileName);
var path = Path.Combine(Server.MapPath("~/UploadFile/"), fileName);
filebase.SaveAs(path);
return Json("File Saved Successfully.");
}
else { return Json("No File Saved."); }
}
catch (Exception ex) { return Json("Error While Saving."); }
问题是当我在 ajax 函数“processData: false”中使用时,我没有在控制器服务器错误 500 中获取 OT ou 数据,但是当删除它时,我在列表中收到 OT 值但不是文件。
我错过了什么?请需要你的帮助
【问题讨论】:
标签: asp.net ajax file controller asp.net-mvc-5