データ取得の概要

最終更新日: 2015年3月9日

適用対象: SharePoint Foundation 2010

この記事の内容
クエリ構文とメソッド構文
ECMAScript でクエリ文字列を使用する
インプレースの読み込みとクエリ可能な読み込み
オブジェクトを取得する方法
オブジェクトを更新する方法
リスト アイテムを取得する方法
リスト アイテムを更新する方法
非同期処理

SharePoint Online で使用可能

新しいクライアント オブジェクト モデルを使用して、特定の SharePoint クライアント オブジェクト (ClientObject、または ECMAScript (JavaScript、JScript)、ClientObject 内) の取得、子オブジェクトと関連プロパティの取得、またはコレクション内の子アイテムの取得を行うことができます。このオブジェクト モデルは、明示的なデータ取得セマンティクスを使用します。機能データを取得するときは、このセマンティクスに従う必要があります。クライアント オブジェクト モデルは、クライアントでローカルに取得されたデータは保持しません。

次の手順にしたがって、データを取得します。

  1. ClientContext() コンストラクター (JavaScript: ClientContext(serverRelativeUrl)) を使用して、クライアント要求のコンテキストを返します。

  2. オブジェクト モデルを使用して、取得するオブジェクトまたはデータの取得元を指定します。

  3. Load<T>(T, []) (JavaScript: load(clientObject)) メソッドを使用して、特定のオブジェクト、コレクション、データを返すインプレースの読み込み、または LoadQuery() (JavaScript: loadQuery(clientObjectCollection, exp)) メソッドを使用して、列挙可能なオブジェクトのコレクションを返すクエリ可能な読み込みのどちらかで、オブジェクトまたはコレクションを読み込みます。

  4. .NET マネージ クライアント オブジェクト モデル、または Silverlight クライアント オブジェクト モデル (ユーザー インターフェイス (UI) を変更しないスレッドからコードが実行される場合) で、同期的な ExecuteQuery() メソッドを呼び出してクエリを実行します。JavaScript オブジェクト モデル内では、または Silverlight オブジェクト モデルが UI を変更するときは、データを取得するために非同期のコールバック モデルが使用され、ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) メソッド (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) を呼び出す必要があります。このメソッドには、要求の成功または失敗を処理するメソッドのパラメーターが含まれています。クエリを実行するメソッド呼び出しが返ると (同期または非同期で)、クエリを起動したオブジェクトでクエリの結果にアクセスできます。

クエリ構文とメソッド構文

統合言語クエリ (LINQ) 構文の両方の形式 (クエリ構文とメソッド構文) をマネージ クライアント オブジェクト モデルで使用して、個々のオブジェクト、特定のオブジェクト プロパティを読み込んだり、オブジェクト コレクションを列挙したりすることができます。

注意

LINQ を使用してクライアント オブジェクト モデルに対するクエリを実行する際、2 点、注意すべき点があります。

  • クライアント オブジェクト モデルに対して LINQ を使用してクエリを作成する場合は、サーバー オブジェクト モデルに対してコードを書き込むときにのみ使用できる LINQ to SharePoint プロバイダーではなく、LINQ to Objects を使用します。

  • クエリが、リストから、リスト アイテムのサブセットを返すよう意図されたとき、LINQ クエリより CAML クエリを使用するほうが効率的です。これは、すべてのリスト アイテムがコンテンツ データベースからフロントエンド Web サーバーに送信され、メモリに読み込まれることによるものです。その後、LINQ フィルターを適用できます。CAML クエリでは、フィルター処理はデータベース サーバーで行われます。このポイントは、リストでアイテムを抽出するクエリにだけ適用されます。Web サイトからリストのサブセットを返すような、その他の種類の LINQ クエリはより効率的です。

クエリ構文は、LoadQuery() メソッド内でのみ使用でき、2 つの手順 (クエリ式の定義とクエリ結果の取得) が必要です。以下のコード例でこのプロセスを示します。このプロセスでは、タイトルが定義されている現 Web サイトのすべてのリストを返します。

var query = from list 
    in clientContext.Web.Lists
    where list.Title != null
    select list;

var result = clientContext.LoadQuery(query);
clientContext.ExecuteQuery();
Dim query = From list In clientContext.Web.Lists _ 
    Where list.Title IsNot Nothing _ 
    Select list

Dim result = clientContext.LoadQuery(query)
clientContext.ExecuteQuery()

メソッド構文は、Load<T>(T, []) メソッドまたは LoadQuery() メソッドで使用でき、ラムダ式を使用します。以下の例では、メソッド構文を使用して、タイトルを持つリストに対して同じクエリを定義します。

clientContext.Load(clientContext.Web, 
    website => website.Lists.Include(
        list => list.Title).Where(
            list => list.Title != null));

clientContext.ExecuteQuery();
clientContext.Load(clientContext.Web, _
    Function(website) website.Lists.Include( _
    Function(list) list.Title).Where( _
    Function(list) list.Title IsNot Nothing))

    clientContext.ExecuteQuery()

前の例では、Include<TSource>(IQueryable<TSource>, []) メソッドを使用して、オブジェクトのコレクションから返されるプロパティを制限してパフォーマンスを向上させる方法を示しています。クエリは、タイトルを持つリストのタイトルのみを返します。

次の例では、クエリ構文を使用して、リストのフィルター可能な非表示でないフィールドを取得します。

FieldCollection collField = oList.Fields;

var query = from field
        in collField
        where field.Hidden == false
        && field.Filterable == true
        select field;

var result = clientContext.LoadQuery(query);

clientContext.ExecuteQuery();
Dim collField As FieldCollection = oList.Fields

Dim query = From field In collField _ 
    Where field.Hidden = False AndAlso field.Filterable = True _ 
    Select field

Dim result = clientContext.LoadQuery(query)

clientContext.ExecuteQuery()

以下の例は、前の例と同じクエリを実行しますが、Load<T>(T, []) メソッドでメソッド構文を使用します。

clientContext.Load(oList,
    list => list.Fields.Where(
    field => field.Hidden == false
        && field.Filterable == true));

    clientContext.ExecuteQuery();
clientContext.Load(oList, Function(list) list.Fields.Where( _
    Function(field) field.Hidden = False _
    AndAlso field.Filterable = True))

    clientContext.ExecuteQuery()

ECMAScript でクエリ文字列を使用する

オブジェクトとデータを取得する JavaScript メソッドでは、LINQ 構文を使用できませんが、文字列式を使用して基本のクエリを定義できます。次の例では、load(clientObject) メソッドを使用し、特定のリストのタイトルと ID のみを取得します。

clientContext.load(oList, 'Title' ,'Id');

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

リスト コレクションと連携するときは、次の例のように Include を指定して、各リストのタイトルと ID のみを返します。

clientContext.load(collList, 'Include(Title, Id)');

別の方法として、オブジェクトまたはコレクションと関連付けられている *PropertyNames クラスのフィールドを使用して、返すプロパティを指定できます。

var propTitle = SP.ListPropertyNames.title;
var propId = SP.ListPropertyNames.id;
clientContext.load(collList, 'Include(' + propTitle + ', ' + propId + ')');

渡すクエリ文字列内に Include キーワードをネストすることもできます。以下の例では、loadQuery(clientObjectCollection, exp) メソッドを使用して、すべてのリストのタイトルと、すべてのリスト内にあるすべてのフィールドのタイトルと説明を取得します。

myListArray = clientContext.loadQuery(collList, 
    'Include(Title,Fields.Include(Title,Description))');

インプレースの読み込みとクエリ可能な読み込み

LINQ ベースのクエリをクライアント オブジェクト モデルで使用するには 2 つの方法があります。インプレースの読み込みを使用する方法とクエリ可能な読み込みを使用する方法です。クエリ可能な読み込みは、別の結果配列でデータを返すのに対し、インプレースの読み込みはオブジェクト自体でデータを返します。

インプレースの読み込みでは、オブジェクトとそのデータを読み込む要求を作成し、複数の要求からのオブジェクト ID を保持します。クライアント コンテキストの Load<T>(T, []) メソッドを使用して、インプレースの読み込みを実行します。以下の例では、現 Web サイトのリストすべてと、その既定のプロパティすべてを読み込みます。クエリ実行後は、コードはリスト コレクション全体と既定のリスト プロパティにアクセスできます。

clientContext.Load(clientContext.Web.Lists); 
clientContext.ExecuteQuery();

クエリ可能な読み込みでは、クエリは返された結果と分離されています。インプレースの読み込みとは異なり、クエリ可能な読み込みでは、オブジェクト ID は保持されません。そのため、コード自体が返されたオブジェクトを保持する必要があります。以下の例では、クエリ構文を使用して Web サイトのすべてのリストを返します。

var query = from list 
    in clientContext.Web.Lists 
    select list;

var result = clientContext.LoadQuery(query);

clientContext.ExecuteQuery();
Dim query = From list In clientContext.Web.Lists _ 
    Select list

Dim result = clientContext.LoadQuery(query)

clientContext.ExecuteQuery()

この例では、コードが連携でき独自に保持する必要がある List オブジェクトの IEnumerable<T> インターフェイスを使用して、結果を満たします。context.Web.Lists は空のままで、合計 0 を返すことに注意してください。リストの合計を取得するには、IEnumerable<T> インターフェイスの Count() を使用する必要があります。

オブジェクトを取得する方法

以下の例では、オブジェクトを読み込んで、そのプロパティにアクセスする方法を示します。リスト オブジェクトは適切に読み込まれるので、リストの既定のプロパティすべてがアクセスすることができます。

ClientContext clientContext =  new ClientContext("http://MyServer/sites/MySiteCollection");
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;

List oList = collList.GetByTitle("Announcements");

clientContext.Load(oList);

clientContext.ExecuteQuery();

Console.WriteLine("Title: {0} Created: {1}", oList.Title, oList.Created);
Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
Dim oWebsite As Web = clientContext.Web
Dim collList As ListCollection = oWebsite.Lists

Dim oList As List = collList.GetByTitle("Announcements")

clientContext.Load(oList)

clientContext.ExecuteQuery()

Console.WriteLine("Title: {0} Created: {1}", oList.Title, oList.Created)
function retrieveWebSite() {
    var clientContext = new SP.ClientContext('/sites/MySiteCollection');
    var oWebsite = clientContext.get_web();
    var collList = oWebsite.get_lists();

    this.oList = collList.getByTitle('Announcements');
    clientContext.load(oList);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert('Title: ' + oList.get_title() + ' Created: ' + oList.get_created());
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

特定のオブジェクトを取得するとき、既定では一部のプロパティにアクセスできません。プロパティにアクセスするには、プロパティを明示的に読み込む必要があります。前の例では、特定のリスト オブジェクトを読み込み、両方のプロパティにアクセスできました。これは、そのプロパティがオブジェクト上で既定で利用できるためです。しかし、この例では、既定で利用できないプロパティ (たとえば OnQuickLaunch (JavaScript: onQuickLaunch)) にアクセスしようとすると、PropertyOrFieldNotInitializedException が返されます。以下の表は、オブジェクトを取得するときに、既定で利用できないプロパティを一覧表示しています。

オブジェクト

プロパティ

Folder

ContentTypeOrder (JavaScript: contentTypeOrder)、UniqueContentTypeOrder (JavaScript: uniqueContentTypeOrder)

List

BrowserFileHandling (JavaScript: browserFileHandling)、DataSource (JavaScript: dataSource)、EffectiveBasePermissions (JavaScript: effectiveBasePermissions)、HasUniqueRoleAssignments (JavaScript: hasUniqueRoleAssignments)、IsSiteAssetsLibrary (JavaScript: isSiteAssetsLibrary)、OnQuickLaunch (JavaScript: onQuickLaunch)、RoleAssignments (JavaScript: roleAssignments)、SchemaXml (JavaScript: schemaXml)、ValidationFormula (JavaScript: validationFormula)、ValidationMessage (JavaScript: validationMessage)

ListItem

DisplayName (JavaScript: displayName)、EffectiveBasePermissions (JavaScript: effectiveBasePermissions)、HasUniqueRoleAssignments (JavaScript: hasUniqueRoleAssignments)、RoleAssignments (JavaScript: roleAssignments)

SecurableObject

HasUniqueRoleAssignments (JavaScript: hasUniqueRoleAssignments)、RoleAssignments (JavaScript: roleAssignments)

Site

Usage (JavaScript: usage)

Web

EffectiveBasePermissions (JavaScript: effectiveBasePermissions)、HasUniqueRoleAssignments (JavaScript: hasUniqueRoleAssignments)、RoleAssignments (JavaScript: roleAssignments)

前の表に一覧表示されているプロパティに加え、オブジェクトのプロパティを介してアクセス可能な親オブジェクトまたは子オブジェクトも既定では利用できません。その結果、前の例に oList.Items.Count を追加すると、アイテムが存在しても、コンソールにはアイテムの実際の数ではなく常に 0 が表示されます。これは、リスト アイテム コレクションが Load<T>(T, []) メソッド (JavaScript: load(clientObject)) で明確に要求されないためです。

オブジェクトを返すときに、既定で利用できないプロパティにアクセスするには、プロパティを明示的に要求する必要があります。前の Load<T>(T, []) (JavaScript: load(clientObject)) メソッド呼び出しの以下のリビジョンでは、OnQuickLaunch (JavaScript: onQuickLaunch) が利用できます。

clientContext.Load(oList,
    list => list.Title,
    list => list.Created,
    list => list.OnQuickLaunch);
clientContext.Load(oList, _
    Function(list) list.Title, _
    Function(list) list.Created, _
    Function(list) list.OnQuickLaunch)
clientContext.load(oList, 'Title', 'Created', 'OnQuickLaunch');

マネージ オブジェクト モデルまたは Silverlight オブジェクト モデルでは、オブジェクトのコレクションと連携する場合、IncludeWithDefaultProperties<TSource>(IQueryable<TSource>, []) メソッドを使用して、既定で利用できないプロパティを読み込まれる各リストに追加します。

注意

JavaScript オブジェクト モデルには、IncludeWithDefaultProperties<TSource>(IQueryable<TSource>, []) メソッドと同等のメソッドはありません。

以下の例は、Web サイトのリストごとに前の例と同じ情報を表示します。

ClientContext clientContext =  new ClientContext("http://MyServer/sites/MySiteCollection");
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;

clientContext.Load(collList,
    lists => lists.IncludeWithDefaultProperties(
        list => list.OnQuickLaunch));

clientContext.ExecuteQuery();

foreach (List oList in collList)
{
    Console.WriteLine("Title: {0} Created: {1} QuickLaunch: {2}", oList.Title, oList.Created, oList.OnQuickLaunch);
}
Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
Dim oWebsite As Web = clientContext.Web
Dim collList As ListCollection = oWebsite.Lists

clientContext.Load(collList, _
    Function(lists) lists.IncludeWithDefaultProperties( _
        Function(list) list.OnQuickLaunch))

clientContext.ExecuteQuery()

Dim oList As List
For Each oList In collList
    Console.WriteLine("Title: {0} Created: {1} QuickLaunch: {2}", oList.Title, oList.Created, oList.OnQuickLaunch)
Next oList

オブジェクトを更新する方法

クライアント オブジェクト モデルを介したオブジェクトの変更は、サーバー オブジェクト モデルを介したオブジェクトの変更と同様です。どちらの場合も、Update メソッドを呼び出す必要があります。ただしクライアント オブジェクト モデルでは、オブジェクトが読み込まれ、ExecuteQuery() または ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) が呼び出されるまで、変更は反映されません。以下の例では、ロードされるリストの説明を変更します。

ClientContext clientContext =  new ClientContext("http://MyServer/sites/MySiteCollection");
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;

List oList = collList.GetByTitle("My List");

oList.Description = "Changed description...";

oList.Update();

clientContext.ExecuteQuery();
Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
Dim oWebsite As Web = clientContext.Web
Dim collList As ListCollection = oWebsite.Lists

Dim oList As List = collList.GetByTitle("My List")

oList.Description = "Changed description..."

oList.Update()

clientContext.ExecuteQuery()
function updateList() {
    var clientContext = new SP.ClientContext('/sites/MySiteCollection');
    var oWebsite = clientContext.get_web();
    var collList = oWebsite.get_lists();

    this.oList = collList.getByTitle('My List');

    oList.set_title('Changed description...');

    oList.update();

    clientContext.load(oList);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert(oList.get_title() + ' created.');
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

前の例では、オブジェクトを変更するときに、クライアントにオブジェクトを読み込む必要がないことに注意してください。

リスト アイテムを取得する方法

多数のリスト アイテムを取得する最も効果的な方法は、CAML (Collaborative Application Markup Language) のクエリを使用して、返すアイテムを指定することです。CamlQuery クラス (JavaScript: CamlQuery) を使用して、クエリを定義し、そのクエリを GetItems(CamlQuery) メソッド (JavaScript: getItems(query)) に渡します。

以下の例では、CamlQuery クラス (JavaScript: CamlQuery) を使用し、リスト内の ID が 100 より小さい 50 のアイテムを返します。Load<T>(T, []) メソッドでは、IncludeWithDefaultProperties<TSource>(IQueryable<TSource>, []) を指定し、DisplayName の取得を追加します。

ClientContext clientContext =  new ClientContext("http://MyServer/sites/MySiteCollection");
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;

List oList = collList.GetByTitle("My List");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Leq>" +
    "<FieldRef Name='ID'/><Value Type='Number'>100</Value>" +
    "</Leq></Where></Query><RowLimit>50</RowLimit></View>";

ListItemCollection collListItem = oList.GetItems(camlQuery);

clientContext.Load(collListItem,
    items => items.IncludeWithDefaultProperties(
    item=>item.DisplayName));

clientContext.ExecuteQuery();

foreach (ListItem oListItem in collListItem)
{
    Console.WriteLine("ID: {0} Display name: {1}", oListItem.Id, oListItem.DisplayName);
}
Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
Dim oWebsite As Web = clientContext.Web
Dim collList As ListCollection = oWebsite.Lists

Dim oList As List = collList.GetByTitle("My List")

Dim camlQuery As New CamlQuery()
camlQuery.ViewXml = "<View><Query><Where><Leq>" + _
    "<FieldRef Name='ID'/><Value Type='Number'>100</Value>" + _
    "</Leq></Where></Query><RowLimit>50</RowLimit></View>"

Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)

clientContext.Load(collListItem, _
    Function(items) items.IncludeWithDefaultProperties( _
        Function(item) item.DisplayName))

clientContext.ExecuteQuery()

Dim oListItem As ListItem
For Each oListItem In collListItem
    Console.WriteLine("ID: {0} Display name: {1}", oListItem.Id, oListItem.DisplayName)
Next oItem

JavaScript オブジェクト モデルには IncludeWithDefaultProperties<TSource>(IQueryable<TSource>, []) メソッドがないので、以下の例では Include を load(clientObject) メソッドと共に使用して、ID の取得と各リスト アイテムの表示名を指定します。

function retrieveListItems() {

    var clientContext = new SP.ClientContext('/sites/MySiteCollection');
    var oList = clientContext.get_web().get_lists().getByTitle('My List');
        
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Leq>' + 
        '<FieldRef Name=\'ID\'/><Value Type=\'Number\'>100</Value>' + 
        '</Leq></Where></Query><RowLimit>50</RowLimit></View>');

    this.collListItem = oList.getItems(camlQuery);
        
    clientContext.load(collListItem, 'Include(Id, DisplayName)');
        
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        
        
}

function onQuerySucceeded(sender, args) {

    var listItemInfo = '';

    var listItemEnumerator = collListItem.getEnumerator();
        
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() + 
            '\nDisplay name: ' + oListItem.get_displayName();
    }

    alert(listItemInfo.toString());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

リスト アイテムを更新する方法

リスト アイテムを変更する場合、インデクサーを使用して変更する列の値を指定し、他のオブジェクトと同じように、Update() (JavaScript: update()) を呼び出してから ExecuteQuery() または ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) を呼び出すことができます。以下の例では、指定された ID を持つアイテムのタイトルを変更します。

ClientContext clientContext =  new ClientContext("http://MyServer/sites/MySiteCollection");
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;

List oList = collList.GetByTitle("My List");
ListItem oItem = oList.GetItemById(5);
oItem["Title"] = "Hello World";
oItem.Update();

clientContext.ExecuteQuery();
Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
Dim oWebsite As Web = clientContext.Web
Dim collList As ListCollection = oWebsite.Lists

Dim oList As List = collList.GetByTitle("My List")

Dim oItem As ListItem = oList.GetItemById(5)
oItem("Title") = "Hello World"
oItem.Update()

clientContext.ExecuteQuery()
function updateListItem() {

    var clientContext = new SP.ClientContext('sites/MySiteCollection');
    var oList = clientContext.get_web().get_lists().getByTitle('My List');

    this.oListItem = oList.getItemById(5);
    oListItem.set_item('Title', 'Hello World');
    oListItem.update();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Item updated.');
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

非同期処理

JavaScript オブジェクト モデルと Silverlight オブジェクト モデル (UI を変更するとき) はどちらも、非同期処理を使用します。そのため、ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) メソッド (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) では、クエリの成功と失敗を処理するコールバック メソッドに対してデリゲートを渡します。この非同期メソッドが処理を完了すると、指定されたコールバック メソッドが呼び出され、クライアントはサーバーからデータを取得します。JavaScript オブジェクト モデルまたは Silverlight オブジェクト モデルを使用してクエリを実行するには、コールバック メソッドと同じ署名を持つデリゲートを定義し、デリゲートを ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) のパラメーターとして渡すことによって呼び出しパスを拡張します。

以下の例では、JavaScript と Silverlight の非同期処理を示します。最初のメソッドの retrieveWebsite は、現在の Web サイトのオブジェクトを取得します。このオブジェクトは、デリゲートが ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) 内で渡される、指定されたコールバック メソッド onQuerySucceeded で利用できるようになります。コールバック メソッドは、取得された Web サイト オブジェクトのタイトルを取得および設定し、2 度目にクエリ実行メソッドを呼び出して、変更内容を反映します。

var oWebsite;
var clientContext;

function retrieveWebsite()
{
   clientContext = SP.ClientContext.get_current();
   oWebsite = clientContext.get_web();
   clientContext.load(oWebsite);
   clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed);
} 
 
function onQuerySucceeded()
{
   oWebsite.set_title(oWebsite.get_title() + " changed in ECMAScript.");
   oWebsite.update();
   clientContext.executeQueryAsync();
}

以下の例は、Silverlight オブジェクト モデルを使用して Web サイト タイトルを設定する方法を示しています。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    public partial class MainPage : UserControl
    {
        ClientContext clientContext;
        Web oWebsite;

        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            clientContext = ClientContext.Current;
            oWebsite = clientContext.Web;

            clientContext.Load(oWebsite,
                website=>website.Title);

            clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
        }

        private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = ChangeTitle;
            this.Dispatcher.BeginInvoke(updateUI);
        }

        private void ChangeTitle()
        {
            oWebsite.Title = oWebsite.Title + " changed in Silverlight.";
            oWebsite.Update();

            clientContext.ExecuteQueryAsync(onTitleChanged, onQueryFailed);
        }

        private void onTitleChanged(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = DisplayTitle;
            this.Dispatcher.BeginInvoke(updateUI);
        }

        private void DisplayTitle()
        {
            MessageBox.Show("Title changed to " + oWebsite.Title);
        }

        private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Request failed. " + args.Message + "\n" + args.StackTrace);
        }

        private delegate void UpdateUIMethod();
    }
}

JavaScript と Silverlight の両方の例では、ClientContext(String) コンストラクター (JavaScript: ClientContext(serverRelativeUrl)) を使用して URL を指定するのではなく、クライアント コンテキストの Current プロパティ (JavaScript: current) を使用して、現在の要求コンテキストを指定します。

SharePoint Foundation Silverlight オブジェクト モデルのコンテキストにおけるデータ取得に関するその他の例と情報については、「Silverlight オブジェクト モデルを使用する」を参照してください。

関連項目

概念

[方法] Web サイトを処理する

[方法] リストを取得する

[方法] リスト アイテムを取得する

[方法] ユーザーとグループを操作する

中心的オブジェクトであるクライアント コンテキスト

クライアント オブジェクト、値オブジェクト、およびスカラー プロパティ

クライアント オブジェクトの作成

クライアント オブジェクト モデルのガイドライン

マネージ オブジェクト モデルと ECMAScript オブジェクト モデルの相違点

一般的なプログラミング作業

その他の技術情報

クライアント クラス ライブラリ

ECMAScript クラス ライブラリ

SharePoint Foundation 2010 のマネージ クライアント オブジェクト モデルの使用

Client Object Model Resource Center (英語)