Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Post rowversion or timestamp of MsSQL using jquery

4.60/5 (3 votes)
22 Jul 2014CPOL1 min read 10.6K   42  
How to post rowversion or timestamp of MsSQL using jquery

Introduction

TIMESTAMP/ROWVERSION provides a row-versioning feature in the table rows. This helps us to manage the synchronization (row update) for multiuse access. But the problem arises when we try to serialize a particular object (which carries a row version value) to json string using JSON.stringify() and post that string to a server using jquery Ajax.

What Is the Problem?

Let's say we have a Rowversion at variable rowVersion.

JavaScript
/*rowVersion from server*/
var rowVersion = [0, 0, 0, 0, 0, 0, 7, 209];
var json = '';

And we want to post json using JSON.stringify() of a particular object which holds this rowVersion using jquery Ajax.

JavaScript
/*this json post would fail, at server RowVersion is null*/
var normalPostObj = {
    RowVersion: rowVersion
};
json = JSON.stringify(normalPostObj);
alert(json);

But at server posted rowVersion is null. The result is the same even if we post the object itself rather than the json string.

What Can We Do?

Extension to handle row versions:

JavaScript
/*rowVersion helper*/
$.timeStampToBase64String = function(data) {
    var str = String.fromCharCode.apply(null, data);
    return btoa(str);
};

Use this extension inside post object to format the rowVersion like:

JavaScript
/*this json post would work just fine, at server rowVersion is as..*/
var modifiedPostObj = {
    RowVersion: $.timeStampToBase64String(rowVersion)
};
json = JSON.stringify(modifiedPostObj);
alert(json);

Can We Use It in Knockout Mapper ?

To do the same thing for Knockout mapper, we have to use this extension inside a replacer function like:

JavaScript
/*Use for knockout =>*/
var timestampReplacer = function(key, value) {
    /*if any property with name RowVersion at the object convert its value*/
    if (key === 'RowVersion' && Array.isArray(value)) {
        return $.timeStampToBase64String(value);
    }
    return value;
};

and use this replacer function in knockout like:

JavaScript
/*important: using normalPostObj rather than the modifiedPostObj*/
json = ko.toJSON(normalPostObj, timestampReplacer);
alert(json);

Check out http://jsfiddle.net/DiponRoy/EUeq3/6/ for a quick preview.

Find Visual Studio 2012 solution for an MVC project in the attachment. In the project, I have used entity framework code first. So if you run the project:

  1. A database with name DbRowVersion will be created (change it from web.config)
  2. And table Student with some seed data

Or follow the example we just talked about. It would work just fine.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)