In my MVC application, I use uploadify for file uploads. The controller action is:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData, FormCollection forms)
{
try
{
if (fileData.ContentLength > 0)
{
var statusCode = Helper.UploadList();
if (statusCode.Equals(System.Net.HttpStatusCode.Created))
return Json(new { success = true });
}
}
return Json(new { success = false });
}
catch (Exception ex)
{
}
I set success= true/false based on the StatusCode and pass it to the onComplete event of uploadify (in a .js file) and show some meaningful alerts.
If Helper.UploadList() throws an exception like:
throw new ArgumentException("Doesn't exist");
How can I catch that exception in the controller action and eventually pass it to the .js file so that I can show an error to the user?
EDIT: If I set return Json(new { success = false }); in the catch block, the value doesn't reach the onComplete.
'onComplete': function (event, queueID, fileObj, response, data) {
if (response == '{"success":true}') {
alert("file uploaded successfully.");
}
else if (response == '{"success":false}') {
alert('file failed to upload. Please try again!');
}
return false;
},
I see this on the UI:
you can do this a little smarter :
public class ErrorModel{
public bool Success{get;set;}
public string Reason{get;set;}
}
public JsonResult Upload(HttpPostedFileBase fileData, FormCollection forms)
{
var model = new ErrorModel { Success = false };
try
{
if (fileData.ContentLength > 0)
{
var statusCode = Helper.UploadList();
if (statusCode.Equals(System.Net.HttpStatusCode.Created))
model.Reason = "File uploaded: " + filename;
model.Success = true;
return JSon(model);
} else {
model.REason = "ERROR: failed to upload file";
return JSon(model);
}
}
}
catch (Exception ex)
{
model.reason = ex.Message;
return JSon(model);
}
javascript:
dataTYpe: 'json',
success: function(data){
if(data.Success){
} else {
alert(data.Reason);
}
}
needs a little extra work and you need to do more checking on your file, but you will find it easier to return meaningful results this way.
you might consider returning a status code
catch(Exception ex)
{
return new HttpStatusCodeResult(400, "Unexpected error uploading");
}
in your js
$.ajax({
url: "http://blaa.com/Upload",
type: "post",
statusCode: {
400: function(e) {
// do whatever
}
}
});
the message can be found in e.statusText, but you must be using IIS or IIS Express to see it, the VS dev server does not send it when debugging - http://forums.asp.net/post/4180034.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.