无法从控制器获取异常以查看

时间:2013-07-15 12:03:17

标签: asp.net-mvc jquery c#-4.0

我在mvc中使用更改事件到文本框时一切正常但我无法在视图中处理控制器抛出的异常。

**VIEW:**



 $("#txtToloc").change( function (event) {

        var toloc= $('#txtToloc').val();
                    var mn = <%= new JavaScriptSerializer().Serialize(ViewData["MODELNUMBER"])%>;
                    var fm = <%= new JavaScriptSerializer().Serialize(ViewData["lblocation"]) %>;
                    var it = <%= new JavaScriptSerializer().Serialize(ViewData["lbinvtype"])%>;
                    var whid = "14";
                    debugger;

            $.ajax({
                url: '<%: Url.Action("GetPartialGraph")%>',
                data: { 'Tolocation' :mn, 'Frmlocation' :fm, 'moNo' :it, 'whid' : whid },
                type: "post",
                cache: false,
                dataType: "html",
                 success: function(result) {
                 alert('yeap');
                  },
       error: function(xhr, status, error) {
                  alert(‘loss’);
                }
            });
        });
        });

从视图中我在控制器中调用动作方法。

    **CONTROLLER.**



  public ActionResult GetPartialGraph(string Tolocation, string Frmlocation, string moNo, string whid)
            {

                string isvalid = "0";
                if (Frmlocation.ToUpper().Trim() == Tolocation.ToUpper().Trim())
                {
                }
                else
                {
                    try
                    {                    
                        ut.Setlocation(Tolocation,Frmlocation,moNo,whid);
                    }

                    catch (iDB2Exception ex)
                    {
                       /* in catch depending upon certain condition I want through diff exception */

                           return View(isvalid);  
                     }


 Everything works fine. But I am unable to bring exception back to view. To show proper message to client. From 

error: function(xhr, status, error) {
              alert(‘loss’);
            }

我将调用另一个函数,并根据返回我将向用户显示消息。我无法从控制器返回异常以显示在视图中。

2 个答案:

答案 0 :(得分:5)

您正在返回视图,因此永远不会执行error函数。您可以将状态代码设置为500并返回JSON结果:

catch (iDB2Exception ex)
{
    Response.StatusCode = 500;
    Response.TrySkipIisCustomErrors = true;
    return Json(new { errorMessage = ex.Message }, JsonRequestBehavior.AllowGet);
}

然后在您的错误处理程序中只需读取此值:

error: function (xhr) {
    if (xhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) {
        var json = $.parseJSON(xhr.responseText);
        alert(json.errorMessage);
    }
}

答案 1 :(得分:0)

只有当HTTP状态代码与200不同时才会执行错误功能。在您发布的代码中,您仍然返回有效视图 - 因此不会执行错误功能。

您可能正在从控制器返回JSON对象。尝试在JSON对象中设置“success”标志,并在“success”方法上验证:

             function(result) {
                 if (result.success)
                     alert('yeap');
              }
相关问题