When coding up Ajax calls in ASP.Net MVC we have a lot of options as far as issuing calls, handling them on the server, and dealing with successes and failures on the client. S
What is the best way to inject the url of the action for the url into the ajax call?
Personally I use HTML5 data-* attributes on DOM elements which I AJAXify. For example:
Foo Bar
and then:
$('#foo').click(function() {
var url = $(this).data('url');
// TODO: perform the AJAX call
});
Of course if the DOM element represents an anchor or a form I would use the native property (action or href).
What are the considerations when choosing JsonBehavior?
No specific considerations. Bear in mind that GET request might be cached by client browsers so you might need to specify { cache: false }
on the client. Oh and of course AllowGet on the server for Json.
What is the best way to handle errors on the server side?
Personally I use FluentValidation.NET to handle validation errors on my view models. There could also be errors coming from the service layer.
What is the best way to handle errors on the client side?
If the server returns JSON I usually have a structure which looks the following:
{ error = 'some error message', result: null }
or:
{ error = null, result: { foo: 'bar' } }
depending on whether there was an error, and on the client:
success: function(data) {
if (data.error != null && data.error != '') {
// error
} else {
// use data.result
}
}
I use the error
callback for everything that is unhandled exceptions on the server in which case simply show some generic error message. A global error handler could be specified using $.ajaxSetup
.
To ease the generation of these JSON results on the server and DRY my actions I use custom action filters which would test whether the request was an AJAX request and if it was an AJAX request test whether there were validation errors added to the ModelState and if they were replace the action result with a custom error JsonResult in order to handle the error case.