【问题标题】:Ajax post returns other page instead of jsonAjax 帖子返回其他页面而不是 json
【发布时间】:2012-08-24 08:37:02
【问题描述】:

我正在尝试通过 ajax post 将序列化数据发布到操作,它应该通过 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:\Demos\SP\CodeBase\SupplierPortal\Demos.SupplierPortal.Web.UI\Controllers\SkillController.cs:line 152 at lambda_method(Closure, ControllerBase, Object[]) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase 控制器,对象 [] 参数)在 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext 控制器上下文,IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 参数)在 System.Web.Mvc.ControllerActionInvoker.c_DisplayClass15.b_12() 在 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter 过滤器,ActionExecutingContext preContext,Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 过滤器,ActionDescriptor actionDescriptor, IDictionary`2 参数)在 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName).Message

【问题讨论】:

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


    【解决方案1】:

    我得到了答案。我的控制器继承自处理异常的基本控制器(受保护的覆盖无效 OnException(ExceptionContext filterContext))。所以,我在这里检查了我的自定义异常,并告诉它不要处理它。

    【讨论】:

      猜你喜欢
      • 2017-03-05
      • 2018-08-27
      • 2020-10-05
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多