javascript - Remove empty properties of knockout viewModel -


this turned out harder thought. have viewmodel use filtering in grids. here is:

var gridfiltersviewmodel = function () {     var self = this;      self.search = ko.observable();     self.sortcolumn = ko.observable();     self.sortdirectionisascending = ko.observable(true);     self.page = ko.observable(1);     self.pagesize = ko.observable(10);     self.pagecount = ko.observable();     self.itemcount = ko.observable(); }; 

the issue i'm faced when send instance of viewmodel towards action method error:

the value 'null' not valid property

this happens because server-side viewmodel properties not accept null , undefined properties of client-side viewmodel when set them nullable. way have server-side viewmodel accept empty properties not send them @ all. attempt @ that:

var gridfiltersviewmodel = function () {     // properties before      self.removeemptyproperties = function () {         (var property in self) {             if (self[property] === null || self[property] === undefined) {                 delete self[property];             }         }     }; }; 

suffice say, not work. end undefined object when method finishes. i've tried converting knockout viewmodel javascript object (using ko.tojs()) before running method same result.

what doing wrong here , how do right?

i construct new json object , return rather try exotic removing properties... this:

 var gridfiltersviewmodel = function () {     var self = this;     self.prop1 = ko.observable(null);     self.prop2 = ko.observable('test');     self.prop3 = ko.observable(undefined);     self.definedproperties = ko.computed(function () {         var json = {};         json.props = "";         (var property in self) {             if (self[property]() !== null && self[property]() !== undefined) {                 json[property] = self[property]();                 if (json.props !== "") {                   json.props += ", ";                                    }                 json.props += property;             }         }         return json;     });     }; 

full example here: https://jsfiddle.net/brettwgreen/ehy7cmud/2/


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -