2012-04-17 56 views
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虛假並將它傳遞給uploadify的onComplete時間(在.js文件),並顯示一些有意義的警報。

如果Helper.UploadList()拋出類似的異常:

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

我怎樣才能捕捉到控制器的行動,異常,並最終把它傳遞給.js文件,這樣我可以顯示一個錯誤的用戶?

編輯: 如果我設置返回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: 

enter image description here

+0

它看起來像你已經有一個'try/catch'塊 - 是問什麼特定的JSON響應將uploadify接受顯示som ething? – Tejs 2012-04-17 19:33:14

+0

如果我在try/catch中設置成功= false。我如何將它返回給.js? – GoldenUser 2012-04-17 19:36:49

+3

'return Json(new {success = false});'?您仍然可以從catch塊返回JSON。 – Tejs 2012-04-17 19:37:16

回答

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

需要一些額外的工作,你需要做更多的檢查你的文件,但您會發現以這種方式返回有意義的結果更容易。

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 dev服務器不會在調試時發送它 - http://forums.asp.net/post/4180034.aspx