I am trying to post serialized data through ajax post to an action and it should return all the model errors through JSON. I have developed sample project and it is returning model errors in json format as I expected. But when I tried to apply the same thing in my project, instead of returning json result, it is returning a page where I have requested.
$.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);
}
}
});
Action:
[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();
}
Model State Action Filter:
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 });
}
};
}
}
}
Please note that the above code working fine in my sample project but it is not working in my live project. I check web.config and everything is same.
The following is the content I found in error.responseText:
Error Found The application has encountered an error, this may be that the page you requested does not exist, if you typed in the url please check that the url is correct. In any case it has suffered and irrevocable, fatal and otherwise irrecoverable error.
Click [Here] to continue.
Demos.SupplierPortal.Web.UI.ModelStateException: Experience Required Please provide Years of Experience at Demos.SupplierPortal.Web.UI.Controllers.SkillController.AddSkill(SkillsViewModel item) in 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 controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary
2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) at System.Web.Mvc.ControllerActionInvoker.<>c_DisplayClass15.b_12() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList
1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName).Message