Friday, 29 May 2009

Using Sys.Observer and jQuery for Template Checkboxes

I was thinking, how do you use those tricky checkboxes with client templates. The problem is that the value bound to the checkbox does not automatically update the data context on the saveChanges() command.

In the client template you can use the sys:commandArgument to return the current dataItem.

<input command="update" commandargument="{{ $dataItem }}" value="Make Live" type="button">

The checkboxes in the template should have the same ID as their datafield

<input id="isReport" value="true" if="isReport==true" checked="checked" type="checkbox">
<input id="isReport" value="true" if="isReport==false" type="checkbox">
<input id="isReport" value="true" if="isReport==null" type="checkbox">

use the clever code:if blocks to display the checkboxes correctly in the first place.

When declaring the template declare a command

fixture = $create(Sys.UI.DataView,
dataProvider: dataContext,
fetchOperation: "categories"
command: saveCommand
null, $get("fixture"));

Then in the saveCommand function loop through all the checkboxes using an if statement to check if it was checked or not and update the dataitem for each with the Sys.Observer.setValue function.

function saveCommand(sender, e) {
//Get the current data item
var data = e.get_commandArgument();
// loop through all the checkboxes and use their id (which is the same as the data field) then add the value back to the dataContext.
$("input:checkbox").each(function() {
var id = $(this).attr("id");
var value = ($(this).attr('checked')) ? true : false;
Sys.Observer.setValue(data, id, value);
dataContext.saveChanges(saved, onfailure);

Wednesday, 27 May 2009

Sys.Observer adding a POJO to the DataContext

Firstly declare a global variable

var myTemplate;

Then add

Sys.Application.add_init(function() {
dataContext = $create(Sys.Data.AdoNetDataContext, { serviceUri: "../../../WebDataService.svc" });

myTemplate = $create(Sys.UI.DataView,
dataProvider: dataContext,
fetchOperation: "DataTable",
fetchParameters: { $filter: "ID eq 1" },
autoFetch: true
command: saveCommand
null, $get("DomID"));

Then add a form input controls for the POJO property.
Then baring in mind that you have retrived just one record get that Data:

var data = myTemplate.get_data();

var myTemplateItem = data[0];

then use the Sys.Observer to add the object to the data context

Sys.Observer.setValue(myTemplateItem , "property", $("#formItem").val()); // Using jQuery selecter get value


And job done the dataContext will update the property to the database.

Very basic but you get the idea. The Sys.Observer is a very powerful tool in the Ajax arsenal.

Thursday, 14 May 2009

New Ajax Control Toolkit Released

The new version of the Ajax control toolkit is available to download from here

I like the look of the text editor control.