【发布时间】:2012-04-18 15:52:18
【问题描述】:
在我的 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:
【问题讨论】:
-
看起来你已经有一个
try/catch块 - 是询问什么特定的 JSON 响应将上传接受以显示一些东西吗? -
如果我在 try/catch 中设置了 success=false。如何将其返回到 .js?
-
return Json(new { success = false });?您仍然可以从 catch 块返回 JSON。 -
正确。但如果发生异常 - 此值不会到达 onComplete 方法。见上文(编辑)
-
如果 ajax 认为它正在返回错误,那么听起来异常没有被您的 try / catch 块捕获。对于 ajax,你的 try catch 块是不可见的。
标签: c# jquery asp.net asp.net-mvc uploadify