c# - asp.net mvc + knockout: Showing validation result from server side logic -


i want pass validation result server client , show message.

without knockout.js simple:

  1. call validation logic.
  2. add validation result modelstate.
  3. every thing hooked automatically. (html.validationmessagefor)

what should when using knockout? best practice here?

do need return modelstate viewmodel? if yes, how should bind validationmessage placeholder? there plugin use?

update 1:

  1. i know how use client side validation libraries (ko validation, jquery validation) not problem.

  2. i know how return model state client using ajax.

  3. the problem is: what standard way of binding errors list, ui elements? need iterate collection , bind them 1 one? there plugin can bind model state object ui?

(just when not using knockout , mvc takes care of , binds them validation message place holders.)

i facing same problem. first tried implement solution (https://datatellblog.wordpress.com/2015/06/26/client-and-server-validation-with-web-api-and-knockout/) didn't work.

my final solution this:

  1. convert modelstate js array:

    var modelstate = null; modelstate = @html.raw(json.encode(viewdata.modelstate.where(k => k.value.errors.any()).select(t => new { key = t.key, value = t.value.errors.select(e => e.errormessage) })));  function getmodelstate() {     return modelstate; } 
  2. after creating view model, add errors it:

     self.adderrors = function (data, modelstate) {     $(data).each(function (dataindex, dataitem) {         var itemmodelstate = $(modelstate).filter(function (filterindex) { return stringstartswith(modelstate[filterindex].key, "addresses[" + dataindex + "]") });          $(itemmodelstate).each(function (index, item) {             var field = item.key.split(".")[1];             if (field === "numberofpositions") {                 $(item.value).each(function (valueindex, valueitem) {                     var name = item.key.replace("[", "\\[").replace("]", "\\]").replace(".", "\\.") + "_error";                     $("#" + name).text(valueitem);                     $("#" + name).removeclass("field-validation-valid").addclass("field-validation-error").show();                 });             }         });      }); }; 

this works @ least in case. hope helps.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -