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:
- call validation logic.
- add validation result modelstate.
- 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:
i know how use client side validation libraries (ko validation, jquery validation) not problem.
i know how return model state client using ajax.
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:
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; }
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
Post a Comment