我想通過ajax post發佈序列化數據到一個動作,它應該通過JSON返回所有模型錯誤。我已經開發了示例項目,並按照我的預期返回了json格式的模型錯誤。但是當我嘗試在我的項目中應用相同的事情時,而不是返回json結果,它返回了我請求的頁面。Ajax post返回其他頁面而不是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找到的內容:
發現錯誤 的應用遇到了一個錯誤,這可能是您請求的頁面不存在,如果你在網址中輸入,請檢查網址是否正確。在任何情況下,它都會遭受和不可挽回的,致命的和不可恢復的錯誤。
點擊[這裏]繼續。
Demos.SupplierPortal.Web.UI.ModelStateException:經驗請 Demos.SupplierPortal.Web.UI.Controllers.SkillController.AddSkill(SkillsViewModel 項目)在 Ë提供工作經驗:\演示\ 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 controller,Object [ ]參數)在 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary paramete rs) System.Web.Mvc.ControllerActionInvoker。 <> C_ DisplayClass15.b _12() 在 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter 濾波器,ActionExecutingContext preContext,函數功能
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參數)在 的System.Web .Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext,String actionName).Message