In addition to having the opportunity to bind interface elements to specific model properties, you can also bind them to expressions. Let's look at some examples:
Razor: <button type="submit" @ko.Bind.Enable(m => m.StringValue.Length > 0)>Add</button> Html: <button type="submit" data-bind="enable : StringValue().length>0">Add</button> Razor: @ko.Bind.Enable(m => m.Items.Count > 0) Html: data-bind="enable : Items().length>0" Razor: @using (ko.If(model => model.Condition1 && model.Condition2)) Html: <!-- ko if: Condition1()&&Condition2() --> Razor: @ko.Html.Span(m => m.Price).Style("color", m => m.Price > 0 ? "black" : "red") Html: <span data-bind="text : Price,style : {color : Price()>0 ? 'black' : 'red'}"></span>
Also, you can create computed properties directly as a model part:
C#: public Expression<Func<string>> FullName() { return () => FirstName + " " + LastName; } Html: viewModel.FullName = ko.computed(function() { try { return this.FirstName()+' '+this.LastName()} catch(e) { return null; } ;}, viewModel);
As you can see from the preceding example, the standard viewModel
will be extended with a special computed property. The advantage of such an approach is that the declared method can be used not only on the server side, but also as a data binding on the client side:
Razor: @ko.Html.Span(m => m.FullName()) Html: <span data-bind="text : FullName"></span>