For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions
@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{
... html for form
}
here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form
$("#btnSubmitFileUpload").click(function(e){
e.preventDefault();
$("#frmUploadTrainingMedia").submit();
});
here is the callback referenced in the AjaxOptions
function displayUploadMediaMsg(d){
var rslt = $.parseJSON(d.responseText);
if (rslt.statusCode == 200){
$().toastmessage("showSuccessToast", rslt.status);
}
else{
$().toastmessage("showErrorToast", rslt.status);
}
}
in the controller method for MVC it looks like this
[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");
}
}