我已经搜索了所有类似的问题,但不幸的是,似乎没有一个对我有用。
我在做什么:我有一个主页,上面有一个上传文档的链接。单击该链接时,它会打开一个带有简单上传表单的模式窗口:
<div id="uploadResults">
@using (Html.BeginForm("_uploadDocument", "Request", FormMethod.Post, new { id = "uploadDoc", enctype = "multipart/form-data" }))
{
<input name="eGuid" value="@ViewBag.eGuid" id="eGuid" type="hidden" />
<input name="result" id="result" value="@ViewBag.result" type="hidden" />
<label for="attachment">Attachment:</label><input type="file" name="attachment" id="attachment" />
<br />
<input type="submit" name="submit" value="Upload" class="txtButton" />
}
</div>
在提交表单时,我想在控制器中调用我的 _uploadDocument 方法。如果上传成功,则关闭模式窗口,以便再次出现父窗口。如果出现错误,则保持模式窗口存在并显示一些通知文本。
我的 httppost 控制器(抱歉,我尝试了几种方法,所以你会看到一些注释掉的位):
[HttpPost]
public void _uploadDocument(string eGuid, HttpPostedFileBase attachment)
{
// store result txt
string result = "";
// check for uploaded file
if (attachment != null && attachment.ContentLength > 0)
{
// get filename
var uploadedFileName = Path.GetFileName(attachment.FileName);
var newFileName = eGuid + "_" + uploadedFileName;
// store to the shared directory
var path = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadDirectory"];
var savePath = Path.Combine(path, newFileName);
try
{
attachment.SaveAs(savePath);
result = "success";
}
catch
{
result = "There was an issue uploading your file";
}
}
else
{
result = "No file was chosen for upload";
}
ViewBag.result = result;
ViewBag.eGuid = eGuid;
//return PartialView("_uploadDocument");
//return Json(new { result = result});
//return Json(result);
}
在上面的表单所在的模式窗口中,我尝试了以下 jquery:
$("#uploadDoc").submit(function (e) {
$.post(this.action, { eGuid: $('#eGuid').val(), attachment: $('#attachment') }, function () {
$("#dialog5").dialog('close');
//alert("In");
//return false;
});
//$.post(this.action, { eGuid: $('#eGuid').val(), attachment: $('#attachment') });
return false;
});
我的结果 - 如果我序列化传递的数据,那么成功函数会触发但未上传文档(因此模式窗口关闭但未上传文档)。
如果我使用上述代码,则文件已上传,但提交后我会进入空白屏幕...
我当然会很感激任何指示!
更新这是从父页面打开模式窗口的代码:
// person look-up modal window
$(function () {
$('#dialog5').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Upload Document',
dataType: "json",
modal: true,
open: function (event, ui) {
var updateArea = $(this).data('area');
//alert(updateArea);
$(this).load('@Url.Action("_uploadDocument", "Request")' + '?eGuid=' + updateArea);
},
cancel: function (event, ui) {
$(this).dialog("close");
}
});
$('.attachDocument').live("click", function () {
var field = this.name;
$('#dialog5').data('area', field).dialog('open');
});
});