Friday, November 12, 2010

Deleting Data Using Silverlight and Javascript Client Object Model

Silverlight

private void Delete_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) =>
    {
        ListItem lastItem = listItems[listItems.Count - 1];
        lastItem.DeleteObject();
        announcements.Update();
        ctx.ExecuteQueryAsync((s1, args1) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                label1.Content = "Last record deleted";
            });
        }, null);
    }, (s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = args.Message;
        });
    });
}

Javascript

function Delete_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 lastItem = listItems.get_item(listItems.get_count() - 1);
        lastItem.deleteObject();
        announcements.update();
        ctx.executeQueryAsync(function (s, args) {
            var console = document.getElementById('DemoConsole');
            console.innerHTML = " Last Item Deleted";
        }, null);
    }, null);
}

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

No comments: