Some data bindings (namely css, style and attr)
are complex. It is possible to call the corresponding @ko.Bind
method for such bindings several times. This samples demonstrates use of several
styles in a single element.
Live example
Model:
Price: (red color for <= 0, black color for >0)
FontSize:
Bindings:
Price:
Model
public class ComplexBindingModel
{
public int Price { get; set; }
public string FontSize { get; set; }
}
Razor
@using PerpetuumSoft.Knockout
@model KnockoutMvcDemo.Models.ComplexBindingModel
@{
var ko = Html.CreateKnockoutContext();
}
<h3>Model:</h3>
Price: @ko.Html.TextBox(m => m.Price) (red color for <= 0, black color for >0)<br />
FontSize: @ko.Html.TextBox(m => m.FontSize)<br />
<h3>Bindings:</h3>
Price: @ko.Html.Span(m => m.Price).Style("color", m => m.Price > 0 ? "black" : "red").Style("fontSize", m => m.FontSize)
@ko.Apply(Model)
Controller
public class ComplexBindingController : BaseController
{
public ActionResult Index()
{
InitializeViewBag("Complex binding");
var model = new ComplexBindingModel
{
Price = -10,
FontSize = "20px"
};
return View(model);
}
}
Html (autogenerated)
<h3>Model:</h3>
Price: <input data-bind="value : Price" type="text" /> (red color for <= 0, black color for >0)<br />
FontSize: <input data-bind="value : FontSize" name="FontSize" type="text" /><br />
<h3>Bindings:</h3>
Price: <span data-bind="text : Price,style : {color : (Price() > 0) ? 'black' : 'red',fontSize : FontSize}"></span>
<script type="text/javascript">
var viewModelJs = {"Price":-10,"FontSize":"20px"};
var viewModel = ko.mapping.fromJS(viewModelJs);
ko.applyBindings(viewModel);
</script>