This post is a tutorial on the new Client-Side Template feature introduced in the Mvc 1.0 release of the Mvc Controls toolkit. I assume that everyone is already familiar with the Client-Side ViewModel & Bindings feature of the Mvc Controls Toolkit.
Client-Side Templates allow a rich UI to be defined just once in a template, and then to use this template to render each of the items in a big collection contained in a Client-Side ViewModel. This way the rich interface is obtained with a low Internet BandWidth cost, since code needed to create the rich UI is sent to the client just once in a template.
Templates are defined a normal Mvc Controls Tool kit templates, by the developer, then they are rendered on the sever and transformed into client-side templates. The template is enriched with some extra code that enables both client and server side validation on the input fields that are created dynamically when the template is instantiated on each Javascript item on the client-side.Once on the client they are instantiated with each of the data items contained into an array of the Client-Side ViewModel.
The insertion of the actual data into the template can be done statically by inserting them just once when the template is instantiated with the data item, or dynamic, in which case we create a permanent client-side binding between the data field of the data item and an html element of the template. In this case each data item acts as a ViewModel of the instance of the template that is associated to it. Dynamic instantiation of a data filed has the advantage that each time the data is changed, the html element it is bound to is automatically updated without requiring the re-instantiation of the whole template. Moreover, dynamic binding can be also two-way, in which case also modifications of the html element can be reflected back on the data field the html elements is bound. Two way bindings are necessary when we want to collect input from the user into the Client-side ViewModel.
As a conclusion dynamic bindings are more flexible, but they are also slower to render, expecially two way bindings, so if one would actually like to put on the screen thousands of items they should be avoided. Unluckly, in case of input fields two way bindings are the only possible choice,since we cannot use rely on the normal post of the input fields if we have thousands of items on the screen but we have to post to the server just the input fields that were actually used.
Thus, the only solution is to put in each o use jus 1-2 input fields connected with two-way bindings to the Client-Side ViewModel, and then when data have to be posted to get rid of all items that don’t contain data actually provided by the user.
Another option is the use of a link that opens a detail windows that has no performance limit on the input fields we can put into it. When the user confirms the data we insert its input into another ViewModel we use just for the post.
In this tutorial, we are mainly interested to show how client side templates work so we will use the first approach of inserting the input fields directly in the template. I will show an example of the second approach in a future post. Moreover, in order to show how the template engine is able to work also with complex controls we will use a TypedTextBox and a DateTimeInput. However, when dealing with huge amount of data, while the TypedTextBox has an acceptable overhead, the DateTimeInput, as all Date inputs has an unacceptable impact on performance, since it is quite slow.
Well…let’s go with the example.
Suppose we want to show a list of products that the user can purchase by just inserting the quantity he would like to receive together with the desired delivery date in the same row displaying the product.
For simplicity we will just display the description of the product. Thus our simple ViewModel description of each product is:
public class ProductView
{
public int Code { get; set; }
public string Description { get; set; }
[Range(0, 4), Display(Name="Quantity", Prompt="Insert Quantity")]
public int? Quantity { get; set; }
[DateRange(DynamicMinimum="MinDeliveryDate", DynamicMaximum="MaxDeliveryDate")]
public DateTime DeliveryDate { get; set; }
[MileStone, ScriptIgnore]
public DateTime MaxDeliveryDate
{
get
{
return DateTime.Today.AddMonths(2);
}
}
[MileStone, ScriptIgnore]
public DateTime MinDeliveryDate
{
get
{
return DateTime.Today.AddDays(2);
}
}
}
We put a range attribute on the Quantity, to allow a maximum purchase of 4 equal products, than we added two read only properties just to define some constraints based on the today date on the delivery date through the DateRangeAttribute as already explained in a previous tutorial.The Milestone attribute declares that the two Date bounds will not be rendered, and the
ScriptIgnoreAttribute, avoid that they are rendered in JSON.
Our full ViewModel is:
public class ToBuyViewModel
{
public List<ProductView> Products { get; set; }
public int LastKey { get; set; }
}
The LastKey property is needed to handle our paging technique: we put on the View an “AddNewPage” button, that when clicked add a new page of products to the ones already shown on the screen. Thus we have no page changes, but just the addition of new products…just a marketing technique to sell more products :)
Since we want to handle our products with cliemt-side templates, we declares that we want to use all our Server-side ViewModel as Client-side ViewModel:
<div >
@{
var clientModel = Html.ClientViewModel("productsClientView", m => m);
var tBinding = clientModel.Template("productViewTemplate", m => m.Products).Get();
}
The first statement just renders the Client-Side ViewModel and returns an object we can use to define client-side bindings as explained in the Client-Side ViewModel documentation. In the second statement we render our Template binding and put it into a string. It says that we want to render all items contained in the Products collection of the Clent-Side ViewModel with the template named “productViewTemplate” that we will define after.
We have to attach this Template binding to the html element that we would like to be filled with the content created by the instantiation of the template. In our case the <tbody> element of our products table:
<table >
<thead>
<tr>
<td><strong>Product</strong></td>
<td><strong>Quantity</strong></td>
<td><strong>Delivery Date</strong></td>
</tr>
</thead>
<tbody data-bind="@tBinding" id="provaScript">
</tbody>
</table>
Now we are ready to define our “productViewTemplate”:
@{var template = Html.ClientTemplate<ProductView>(
"productViewTemplate",
_S.H<ProductView>(
@<tr>
<td>
@item._D(m => m.Description)
</td>
<td>
@item.TypedTextBoxFor(m => m.Quantity)
@item.ValidationMessageFor(m => m.Quantity, "*")
</td>
<td>
@item.DateTimeFor(m => m.DeliveryDate, DateTime.Today,
false).Date()
</td>
</tr>
), true);}
@template
The client-side template is rendered with the ClientTemplate helper, that is strongly typed with the type of the items the template will be instantiated with. The first argument is the template name, while the second argument is an Mvc Controls Toolkit template defined through an in-line Razor helper, as explained in the documentation about templates. Please refers to this documentation for details about Mvc Controls Toolkit templates. I just remember you that the item variable contains an HtmlHelper<ProductView> object that we can use to render our controls.
The bindings of the TypedTextBox with the Quantity, and the one of the DateTimeInput with the DeliveryDate of each ProductView object in the Products collection of our Client-Side ViewModel are deined automatically by the Mvc Controls Toolkit since we have turned on the implicit bindings definition of input fields feature of the client side template by setting to true the last parameter of the ClientTemplate helper. The Description is inserted into the template statically (that is once for all when the template is instantiated) with the _D helper.This helper renders its parameter enclosed in a span element and with the formattion defined in a FormatAttribute.
There is also an _F helper that displays its parameter with formatting but without the span element, and the _P helper that displays its parameter in a rough format without any formatting.
As you can see, thanks, to both the implicit binding definition of input fields and to The _D helper we have defined the Client-Side template in exactly the same way we would have defined a Server-Side template! This make the use of Client-Side template straigthforward and enhance the re-usability of templates.
Let’ handle paging now. We need just to ask a new page of products through an Ajax call to an action method:
<input id="Button1" type="button" value="AddNewPage" />
@{
string nextPageUrl=Url.Action("Index", "Shopping", new {json=true});
}
<script language='javascript' type='text/javascript'>
$(document).ready(function () {
$('#Button1').bind('click', function () {
$.getJSON("@MvcHtmlString.Create(nextPageUrl)" + "&startFrom=" + productsClientView.LastKey(), function (data) {
if (data != null && data.Products != null) {
data = ko.mapping.fromJS(data);
for (var i = 0; i < data.Products().length; i++) {
productsClientView.Products.push(data.Products()[i]);
}
productsClientView.LastKey(data.LastKey());
}
});
});
});
</script>
We first build the Url string of the request. We pass a json=true parameter to our action method, just to say we want the answer in JSON(it is not a general convention…but just the way we have programmed our action method). At run time we add also the parameter that specifies the code of the product to start with. When data arrive we push it in our original Products collection…and miracle of the Template binding, new templates are instantiated automatically for the new products! Finally we update, our LastKey property to be ready for the next page request.
When the user clicks the “submit” button, in order to avoid sending a big amount of useless data to the server, we copy into another Client-Side ViewModel, that is located into another form, just the items with a Quantity greater than 0, and then submit this other form. This way, since we are submitting another form, we avoid sending all input fields that we have created to the server, and we avoid also sending our main Client-Side ViewModel that might have become very big after a lot of new page requests.
Below the other form with the secondary ViewModel:
@using (Html.BeginForm("Confirm", "Shopping"))
{
var confirmModel = Html.SAClientViewModel(
"confirmModel",
new PurchaseConfirmationView(),
initialSave: false,
applyBindings: false);
}
We rendered our secondary Client-Side ViewModel differently from our main Client-Side ViewModel since it is not part of the Server-Side ViewModel,l but it is destined to an Action method that uses a different type of ViewModel. The SAClientViewModel helpers accepts directly an instance of an object instead of a LambdaExpression, so we can pass it any ViewModel.
Finally, below the javascriot function that fill the secondary Client-Side ViewModel:
<script language='javascript' type='text/javascript'>
productsClientView.submitProductsChosen = function () {
confirmModel.Products = new Array();
for (var i = 0; i < this.Products().length; i++) {
var quantity = this.Products()[i].Quantity();
if (quantity != null && quantity != 0) {
confirmModel.Products.push(this.Products()[i]);
}
}
if(confirmModel.Products.length>0)
confirmModel.saveAndSubmit();
};
</script>
That’s all! The full code is contained in the RazorClientTemplating file in the Mvc Controls Toolkit download page. Download it and enjoy!
Francesco
Tags: MVC Controls Toolkit, Templates, MVC, Client Side ViewModel, Knockout, Bindings