Item Template and complex expressions

May 31, 2013 at 7:49 PM
Edited May 31, 2013 at 7:59 PM
How do I bind to a complex expression in a client template. For example, I tried this:
@{
  var itemBindings = item.ItemClientViewModel();
  var prefix = "/";
}
<a data-bind="@itemBindings.Attr("href", m=> prefix + m.SomeProperty)).Get()">
However, this just renders as:
<a data-bind="$data">
As another example, the following:
@item._if(m => m.A == m.B)
Renders as:
<!--  ko template: {if: $data, templateEngine: ko.nativeTemplateEngine.instance, afterRender: null, processingOptions: {unobtrusiveClient: true}}  -->
Coordinator
Jun 1, 2013 at 3:48 PM
No, lambda expressions are not compiled into javascript conditions. This wouldn't work, because you usually compare an item property with some other javascript variables that is not necessarely defined in the item itself. Thus the only way is to insert item properties that you may specify with lambda expressions into "holes" in a javascript string.

You must supply a format string with holes(that represent a javascript condition) and all lambda expressionss that you want to put in the holes. See documentation .

So you will have something like :

@Html._if(m => m.Quantity.Total, format: "{0}<4"),

If there are more "holes" to be filled with other property of the item you must supply the otherExpressions parameter that is an array of other lambdaExpressions.

For instance to verify that two properties of the item are equal:
@{var bb = item.ClientBindings();}
@Html._if(m => m.A, format: "{0} == {1}", otherExpressions: new LambdaExpression[]{bb.L(m => m.B)}),

That is the first LambdaExpression is the first expression, if you need further LambdaExpressions representing proprties you supply them in the otherExpressions parameter.

The .L method is used just to have VisualStudio help when writing each element of the array of LambdaExpressions