Skip to content

Instantly share code, notes, and snippets.

@fjeldstad
Created April 20, 2012 13:45
Show Gist options
  • Save fjeldstad/2428788 to your computer and use it in GitHub Desktop.
Save fjeldstad/2428788 to your computer and use it in GitHub Desktop.
Idea for a utility method that maps ASP.NET MVC ModelState to "_ValidationErrors" observable array properties on a Knockout view model.
(function (lab, $, undefined) {
lab.Utils = new (function () {
return {
UpdateValidationErrors: function (viewModel, modelState) {
var keySeparator = new RegExp("[.\\[\\]]+");
for (var key in modelState) {
if (!modelState[key]) {
continue;
}
var errors = modelState[key].Errors;
var propertyChain = key.split(keySeparator);
var currentObject = viewModel;
var currentPropertyName = propertyChain.shift();
var targetObject = null;
while (currentObject && currentObject[currentPropertyName]) {
if (propertyChain.length === 0) {
targetObject = currentObject[currentPropertyName];
break;
}
currentObject = ko.utils.unwrapObservable(currentObject[currentPropertyName]);
currentPropertyName = propertyChain.shift();
}
if (targetObject) {
targetObject._ValidationErrors($.map(errors, function (item) {
return item.ErrorMessage;
}));
delete modelState[key];
}
}
// All remaining modelstate errors are "global"
var globalErrors = [];
for (key in modelState) {
globalErrors = globalErrors.concat($.map(modelState[key].Errors, function (item) {
return item.ErrorMessage;
}));
}
viewModel._ValidationErrors(globalErrors);
}
};
})();
} (window.lab = window.lab || {}, jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment