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
.
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.
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:
$.timeStampToBase64String = function(data) {
var str = String.fromCharCode.apply(null, data);
return btoa(str);
};
Use this extension inside post
object to format the rowVersion
like:
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:
var timestampReplacer = function(key, value) {
if (key === 'RowVersion' && Array.isArray(value)) {
return $.timeStampToBase64String(value);
}
return value;
};
and use this replacer function in knockout like:
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:
- A database with name
DbRowVersion
will be created (change it from web.config) - And table
Student
with some seed data
Or follow the example we just talked about. It would work just fine.