As all of you aware, DTO pattern allows us to encapsulate
data and send it from one system to another and thereby decoupling the two
systems. With this pattern we can send just the amount of data that is needed.
In ASP.NET MVC this is sometimes called as View Models. But the idea is same,
decouple the systems, encapsulate all the necessary data and send it along the
pipe.
Single Page Application (SPA) is all together a different
paradigm. Here most of the ux processing is done in the browser and the server
is used to store and return data. In a sense this is a truly decoupled
environment. In this environment we need a proper way to exchange data, errors,
messages and other information.
In this blog I will show you how I standardized the data
exchange between javascript and WebAPI. As I need a consistent mechanism to
send data, errors and success messages to javascript from WebAPI, I came up
with the below signature.
public class AjaxModel<T>
{
public bool Success { get; set; }
public string Message { get; set; }
public T Model { get; set; }
}
As you see, I defined a generic class which shuttles the
data using generic object. In addition it also carries a boolean variable specifying
whether the call is success or not and a message which can contain positive or
negative message.
With this object I can send any type of data from the Web
API to the client along with the status. The client on receiving this message
can check the status before processing the data. Here is my generic ajax post
code
function httpPost(url, data) {
var self = this;
self.loading(true);
url =
vm.virtualDirectory + '/' + url;
return http.post(url, data).then(function (returndata) {
self.loading(false);
if (returndata.Success === false) {
toastr.error(returndata.Message);
}
return returndata;
}).fail(function (e) {
self.loading(false);
var message = '';
if (e.responseJSON.ExceptionMessage !== undefined)
message = e.responseJSON.ExceptionMessage;
else
message = e.responseJSON.Message;
toastr.error(message);
});
}
As you see, I check for the success from the ajax call. If
there is an error, I show the error message. Otherwise continue with my
javascript.
Having a standardized DTO object enables me to decouple the
layers and write generic code which handles all my ajax requests and also
preprocess errors that I get from the server.