Thursday, November 11, 2010

Updating Data Using Silverlight and Javascript Client Object Model

Silverlight

private void Update_Click(object sender, RoutedEventArgs e)
{
    ClientContext ctx = new ClientContext("Your Server Here");
    CamlQuery query = new CamlQuery();
    query.ViewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    List announcements = ctx.Web.Lists.GetByTitle("Announcements");

    ListItemCollection listItems = announcements.GetItems(query);
    ctx.Load(listItems);
    ctx.ExecuteQueryAsync((s, args) =>
    {
        foreach (var item in listItems)
        {
            item["Title"] = "Updated";
            item.Update();
        }
        ctx.ExecuteQueryAsync((s1, args1) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                label1.Content = "Records Updated";
            });
        }, null);
    }, (s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = args.Message;
        });
    });
}

Javascript

function Update_Click() {
    var ctx = new SP.ClientContext.get_current();
    var query = new SP.CamlQuery();
    query.viewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    var announcements = ctx.get_web().get_lists().getByTitle("Announcements");
    var listItems = announcements.getItems(query);

    ctx.load(listItems, "Include(Title)");
    ctx.executeQueryAsync(function (s, args) {
        var itemEnum = listItems.getEnumerator();
        while (itemEnum.moveNext()) {
            var item = itemEnum.get_current();
            item.set_item("Title", "JavaScript Update");
            item.update();
        }
        ctx.executeQueryAsync(function (s, args) {
            var console = document.getElementById('DemoConsole');
            console.innerHTML = "JavaScript Update Completed";
        }, null);
    }, null);
}

For more information on Silverlight and JavaScript Client Object Model, see below:

No comments: