Suppose you have the following controller action
[HttpPost]
public ActionResult Save( CustomerModel model )
{
if (!ModelState.IsValid) {
//Invalid - redisplay form with errors
return PartialView("Customer", model);
}
try {
//
// ...code to save the customer here...
//
return PartialView( "ActionCompleted" );
}
catch ( Exception ex ) {
ActionErrorModel aem = new ActionErrorModel() {
Message = ex.Message
};
return PartialView( "ActionError", aem );
}
}
And suppose you call this action using jQuery:
$.ajax({
type: "post",
dataType: "html",
url: "/Customer/Save",
sync: true,
data: $("#customerForm").serialize(),
success: function(response) {
/*
??????
*/
},
error: function(response) {
}
});
I would like to be able to distinguish between the results I am getting to handle them in different ways on the client. In other words how can I understand that the action
- returned the same model because has not passed validation
- returned one of the views that represents error info/messages
Any suggestion?
One way to handle this is to append a custom HTTP header to indicate in which case we are falling:
And on the client side test this header:
The benefit of this is that the custom HTTP header will always be set in the response no matter what content type you’ve returned. It will also work with JSON, XML, …
Remark 1: To avoid cluttering you controller action with all those
Response.AppendHeaderinstructions you could write a customActionResultallowing you to directly specify the value of this header so that you simplyreturn this.MyPartialView("Customer", model, "case 1")Remark 2: Remove this
sync: trueattribute from the request because it makes my eyes hurt (in fact I think you meantasync: 'false').