我正在尝试实施Knockout Validation和Knockout Mapping。我有一个ASP.Net MVC WebAPI,它将JSON数据发送到我的客户端,我在我的模型中将JSON映射到observables:
视图模型:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null,
decorateElement: true,
errorClass: 'error'
});
var MakePaymentViewModel = function ()
{
var mapDataFromJson = function (jsonFromServer)
{
var model = ko.mapping.fromJS(jsonFromServer);
self.PaymentAmount(model.PaymentAmount());
self.MakePaymentTo(model.MakePaymentTo());
self.MakePaymentOn(model.MakePaymentOn());
};
var self = this;
/* MAKE PAYMENT MODEL*/
self.PaymentAmount = ko.observable().extend({ required: { message: 'required'}});
self.MakePaymentTo = ko.observable().extend({ required: { message: 'required'}});
self.MakePaymentOn = ko.observable().extend({ required: { message: 'required' }});
self.Errors = ko.validation.group(self);
self.MapDataFromServer = function (jsonFromServer)
{
mapDataFromJson(jsonFromServer);
};
self.DoPaymentConfirmation = function ()
{
console.log('error count: ' + self.Errors().length);
};
};
这是我的观点:
<form id="MakePaymentForm" autocomplete="off">
<div class="input-wrapper">
<label for="SendingAmount" class="text-left">I am sending <small>*</small></label>
<input id="PaymentAmount" type="text" data-bind="value: PaymentAmount"/>
</div>
<div class="input-wrapper">
<label for="MakePaymentTo" class="text-left">to <small>*</small></label>
<input id="MakePaymentTo" type="text" data-bind="value: MakePaymentTo"/>
</div>
<div class="input-wrapper">
<label for="MakePaymentOn" class="text-left">on <small>*</small></label>
<input name="MakePaymentOn" id="MakePaymentOn" type="text" data-bind="value: MakePaymentOn"/>
</div>
<button type="submit" class="small radius" data-bind="click: DoPaymentConfirmation">Send</button>
</form>
我认为发生的事情是我第一次从服务器获取数据时,JSON的数据为空:
{"PaymentAmount":null,"MakePaymentTo":null,"MakePaymentOn":null}
因此,mapDataFromJson函数使用null数据填充observable并触发验证规则,因此UI会在用户输入任何数据之前立即显示错误消息。
有关如何解决此问题的任何想法?我是Knockout的新手,所以我可能没有正确地做到这一点。谢谢你的时间。
答案 0 :(得分:0)
感谢杰米指出我正确的方向。以下是我为解决问题所做的工作:
var mapDataFromJson = function (jsonFromServer)
{
var model = ko.mapping.fromJS(jsonFromServer);
if (model.PaymentAmount() != null)
{
self.PaymentAmount(model.PaymentAmount());
}
if (model.MakePaymentTo() != null)
{
self.MakePaymentTo(model.MakePaymentTo());
}
if (model.MakePaymentOn() != null)
{
self.MakePaymentOn(model.MakePaymentOn());
}
};
然后在绑定到提交按钮的函数中执行此操作:
self.DoPaymentConfirmation = function ()
{
if (self.Errors().length == 0)
{
//POST TO SERVER
}
else
{
self.Errors.showAllMessages();
}
};