Ajax post返回其他页面而不是json

时间:2012-08-29 16:58:39

标签: c# ajax asp.net-mvc json exception-handling

我试图通过ajax帖子将序列化数据发布到一个动作,它应该通过JSON返回所有模型错误。我开发了示例项目,并按照我的预期返回json格式的模型错误。但是当我尝试在我的项目中应用相同的东西时,它不是返回json结果,而是返回我请求的页面。

$.ajax(
{
    url: action,
    type: "POST",
    cache: false,
    dataType: "json",
    data: jsonSerializedData,
    success: function (result) {
        getValidationSummary($('#titleseparator')).html('');
        callback(result);
    },
    error: function (error, errorCode) {
        if (error.status == '530') {
            alert(error);
        }
        else if (error.status = '400' && error.responseText != '') {
            var jsonResponse = jQuery.parseJSON(error.responseText);

          //error.responseText should return json result but it returns a page with full view(which is the current page where I have requested)
        }
        else {
            alert(error);
        }
    }
});

动作:

[HttpPost]
[HandleModelState]
public ActionResult CreateEmployee(Employee emp)
{

    if (emp.Name.Length <= 5)
        ModelState.AddModelError("Name", "Name should contain atleast 6 characters");
    if (emp.Address.Length <= 10)
        ModelState.AddModelError("Address", "Address should contain atleast 11 characters");

    if (!ModelState.IsValid)
    {
        ModelState.AddModelError(string.Empty, "Please correct errors");
        throw new ModelStateException(ModelState);
    }
     return json();
}

模型状态操作过滤器:

public sealed class HandleModelState : FilterAttribute, IExceptionFilter
{
    /// <summary>   
    /// Called when an exception occurs and processes <see cref="ModelStateException"/> object.   
    /// </summary>  
    /// <param name="filterContext">Filter context.</param>  
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        if (filterContext.Exception != null
            && typeof(ModelStateException).IsInstanceOfType(filterContext.Exception)
            && !filterContext.ExceptionHandled)
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.StatusCode = 400;
            var errors = (filterContext.Exception as ModelStateException).Errors;
            filterContext.Result = new JsonResult
          {
              Data = new
              {
                  HasErrors = errors.Count > 0,
                  Errors = errors.Select(e => new { Name = e.Key, Error = e.Value });
              }
          };
        }
    }
}

请注意,上面的代码在我的示例项目中工作正常,但它在我的实时项目中不起作用。我检查web.config,一切都一样。

以下是我在error.responseText中找到的内容:

  

发现错误   应用程序遇到错误,这可能是您请求的页面不存在,如果您在URL中键入,请检查该URL是否正确。在任何情况下,它都遭受了不可挽回的,致命的和无法恢复的错误。

     

单击[此处]继续。

     

Demos.SupplierPortal.Web.UI.ModelStateException:需要的经验请提供多年的经验   Demos.SupplierPortal.Web.UI.Controllers.SkillController.AddSkill(SkillsViewModel   项目)   E:\演示\ SP \基本代码\ SupplierPortal \ Demos.SupplierPortal.Web.UI \ \控制器SkillController.cs:行   152 at lambda_method(Closure,ControllerBase,Object [])at   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase   controller,Object []参数)at   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext   controllerContext,IDictionary 2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2   参数)at   System.Web.Mvc.ControllerActionInvoker&LT;&GT; C_ DisplayClass15.b _12()   在   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter   filter,ActionExecutingContext preContext,Func 1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList 1个过滤器,ActionDescriptor actionDescriptor,   IDictionary`2参数)at   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext   controllerContext,String actionName).Message

1 个答案:

答案 0 :(得分:0)

我得到了答案。我的控制器继承自处理异常的basecontroller(protected override void OnException(ExceptionContext filterContext))。所以,我在这里检查了我的自定义异常,并告诉它不要处理它。