对于MVC而言,这是一个更简单的方法。您需要使用Ajax表单并设置AjaxOptions
@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{
... html for form
}
这是提交代码,它在“文档准备就绪”部分中,并与按钮的onclick事件相关联以提交表单
$("#btnSubmitFileUpload").click(function(e){
e.preventDefault();
$("#frmUploadTrainingMedia").submit();
});
这是AjaxOptions中引用的回调
function displayUploadMediaMsg(d){
var rslt = $.parseJSON(d.responseText);
if (rslt.statusCode == 200){
$().toastmessage("showSuccessToast", rslt.status);
}
else{
$().toastmessage("showErrorToast", rslt.status);
}
}
在MVC的控制器方法中,它看起来像这样
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// there is only one file ... do something with it
}
return Json(new
{
statusCode = 200,
status = "File uploaded",
file = "",
}, "text/html");
}
else
{
return Json(new
{
statusCode = 400,
status = "Unable to upload file",
file = "",
}, "text/html");
}
}