0

在我的 MVC 应用程序中,我使用 uploadify 进行文件上传。控制器动作是:

[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)
{       
}   

我根据 StatusCode 设置了 success= true/false 并将其传递给 uploadify 的 onComplete 事件(在 .js 文件中)并显示一些有意义的警报。

如果 Helper.UploadList() 抛出如下异常:

throw new ArgumentException("Doesn't exist");   

如何在控制器操作中捕获该异常并最终将其传递给 .js 文件,以便向用户显示错误?

编辑: 如果我设置 return Json(new { success = false }); 在 catch 块中,该值未达到 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:

在此处输入图像描述

4

2 回答 2

0

你可以考虑返回一个状态码

catch(Exception ex)
{
    return new HttpStatusCodeResult(400, "Unexpected error uploading");
}

在你的 js 中

$.ajax({
    url: "http://blaa.com/Upload",
    type: "post",
    statusCode: {
        400: function(e) {
            // do whatever
        }
    }
});

该消息可以在e.statusText中找到,但您必须使用IIS或IIS Express才能看到它,VS开发服务器在调试时不会发送它 - http://forums.asp.net/post/4180034.aspx

于 2012-04-18T07:39:18.133 回答
0

你可以更聪明地做到这一点:

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);
      }
}

需要一些额外的工作,并且您需要对文件进行更多检查,但是您会发现以这种方式返回有意义的结果更容易。

于 2012-04-17T22:09:55.170 回答