Monday, June 30, 2014


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;
        url = vm.virtualDirectory + '/' + url;
        return, data).then(function (returndata) {
            if (returndata.Success === false) {
            return returndata;
            }).fail(function (e) {
                var message = '';
                if (e.responseJSON.ExceptionMessage !== undefined)
                    message = e.responseJSON.ExceptionMessage;
                    message = e.responseJSON.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.

No comments:

Post a Comment