Partager via


Procédure : utiliser des composants WebPart dans une page

Dernière modification : samedi 30 avril 2011

S’applique à : SharePoint Foundation 2010

Dans cet article
Mise à jour du titre d'un composant WebPart
Ajout d'un composant WebPart à une page
Suppression d'un composant WebPart d'une page

Disponible dans SharePoint Online

Utilisez les classes de l'espace de noms Microsoft.SharePoint.Client.WebParts (JavaScript: SP.WebParts) pour employer des composants WebPart dans l'ensemble du modèle objet client. La classe LimitedWebPartManager (JavaScript: LimitedWebPartManager) permet d'accéder à la collection de composants WebPart sur une page SharePoint dans une étendue personnelle ou partagée via la propriété WebParts (JavaScript: webParts).

Mise à jour du titre d'un composant WebPart

L'exemple suivant modifie le titre du deuxième composant WebPart dans la collection des composants WebPart sur la page par défaut Default.aspx du site Web spécifié. L'exemple utilise une expression de requête LINQ pour retourner seulement le titre de chaque composant WebPart, et appelle la méthode SaveWebPartChanges() (JavaScript: saveWebPartChanges()) pour enregistrer les modifications effectuées. La méthode ExecuteQuery() ou ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) est appelée deux fois, la première pour retourner la collection de composants WebPart de façon que le code puisse vérifier que les composants WebPart existent sur cette page, et la seconde fois pour effectuer les modifications dans la base de données.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SampleCode
{
    class UpdateWebPartTitle
    {
        static void Main()
        {
            ClientContext oClientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            File oFile = oClientContext.Web.GetFileByServerRelativeUrl("Default.aspx");
            LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            oClientContext.Load(limitedWebPartManager.WebParts,
                wps => wps.Include(
                wp => wp.WebPart.Title));

            oClientContext.ExecuteQuery();

            if (limitedWebPartManager.WebParts.Count == 0)
            {
                throw new Exception("No Web Parts on this page.");
            }

            WebPartDefinition oWebPartDefinition = limitedWebPartManager.WebParts[1];
            WebPart oWebPart = oWebPartDefinition.WebPart;
            oWebPart.Title = "My New Web Part Title";

            oWebPartDefinition.SaveWebPartChanges();

            oClientContext.ExecuteQuery();
         }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint.Client.WebParts

Namespace Microsoft.SDK.SharePointServices.Samples
    Class UpdateWebPartTitle

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim serverRelativeUrl As String = "/sites/MySiteCollection/Default.aspx"

            Dim oClientContext As New ClientContext(siteUrl)
            Dim oFile As File = oClientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl)
            Dim limitedWebPartManager As LimitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared)

            oClientContext.Load(limitedWebPartManager.WebParts, _
                                Function(wps) wps.Include( _
                                    Function(wp) wp.WebPart.Title))

            oClientContext.ExecuteQuery()

            If limitedWebPartManager.WebParts.Count = 0 Then
                Throw New Exception("No Web Parts on this page.")
            End If

            Dim oWebPartDefinition As WebPartDefinition = limitedWebPartManager.WebParts(1)
            Dim oWebPart As WebPart = oWebPartDefinition.WebPart
            oWebPart.Title = "My New Web Part Title"

            oWebPartDefinition.SaveWebPartChanges()

            oClientContext.ExecuteQuery()

        End Sub
    End Class
End Namespace
siteUrl = '/sites/MySiteCollection';
serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';

function updateWebPartTitle() {

    this.clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);

    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    this.collWebPart = limitedWebPartManager.get_webParts();

    clientContext.load(collWebPart);

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

function changeTitle() {

    if (!collWebPart.get_count()) {
        alert('No Web Parts on this page.');
    }

    var oWebPartDefinition = collWebPart.get_item(2);
    this.oWebPart = oWebPartDefinition.get_webPart();
    oWebPart.set_title('My New Web Part Title');

    oWebPartDefinition.saveWebPartChanges();

    clientContext.load(oWebPart, 'TitleUrl');

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

function onQuerySucceeded() {

    alert('Title changed for Web Part: ' + this.oWebPart.get_titleUrl());
}

function onQueryFailed(sender, args) {

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

Ajout d'un composant WebPart à une page

L'exemple suivant ajoute un composant WebPart éditeur de contenu personnalisé en tant que deuxième WebPart, en ordre, dans la zone de gauche de la page Default.aspx d'un site Web spécifié. L'exemple définit l'XML pour le composant WebPart, passe cette chaîne à la méthode ImportWebPart(String) (JavaScript: importWebPart(webPartXml)), et appelle la méthode AddWebPart(WebPart, String, Int32) (JavaScript: addWebPart(webPart, zoneId, zoneIndex)) pour ajouter le composant WebPart à la page.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SampleCode
{
    class AddWebPart
    {
        static void Main()
        {
            ClientContext oClientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            File oFile = oClientContext.Web.GetFileByServerRelativeUrl("Default.aspx");
            LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            string xmlWebPart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
                "<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + 
                " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + 
                " xmlns=\"https://schemas.microsoft.com/WebPart/v2\">" + 
                "<Title>My Web Part</Title><FrameType>Default</FrameType>" + 
                "<Description>Use for formatted text, tables, and images.</Description>" +
                "<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>" +
                "<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>" +
                "<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>" +
                "<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>" +
                "<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />" +
                "<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />" +
                "<MissingAssembly>Cannot import this Web Part.</MissingAssembly>" +
                "<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />" +
                "<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, " + 
                "PublicKeyToken=94de0004b6e3fcc5</Assembly>" +
                "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" +
                "<ContentLink xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
                "<Content xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
                "<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>" + 
                "<PartStorage xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>";
            
            WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(xmlWebPart);

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "Left", 1);

            oClientContext.ExecuteQuery();            
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint.Client.WebParts

Namespace Microsoft.SDK.SharePointServices.Samples
    Class AddWebPart

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim serverRelativeUrl As String = "/sites/MySiteCollection/Default.aspx"

            Dim oClientContext As New ClientContext(siteUrl)
            Dim oFile As File = oClientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl)

            Dim limitedWebPartManager As LimitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared)

            Dim xmlWebPart As String = "<?xml version='1.0' encoding='utf-8'?>" + _
            "<WebPart xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + _
            " xmlns:xsd='http://www.w3.org/2001/XMLSchema'" + _
            " xmlns='https://schemas.microsoft.com/WebPart/v2'>" + _
            "<Title>My Web Part</Title><FrameType>Default</FrameType>" + _
            "<Description>Use for formatted text, tables, and images.</Description>" + _
            "<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>" + _
            "<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>" + _
            "<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>" + _
            "<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>" + _
            "<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />" + _
            "<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />" + _
            "<MissingAssembly>Cannot import this Web Part.</MissingAssembly>" + _
            "<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />" + _
            "<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, " + _
            "PublicKeyToken=94de0004b6e3fcc5</Assembly>" + _
            "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" + _
            "<ContentLink xmlns='https://schemas.microsoft.com/WebPart/v2/ContentEditor' />" + _
            "<Content xmlns='https://schemas.microsoft.com/WebPart/v2/ContentEditor'>" + _
            "<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>" + _
            "<PartStorage xmlns='https://schemas.microsoft.com/WebPart/v2/ContentEditor' /></WebPart>"


            Dim oWebPartDefinition As WebPartDefinition = limitedWebPartManager.ImportWebPart(webPartXml)

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "Left", 1)

            oClientContext.ExecuteQuery()

        End Sub
    End Class
End Namespace
siteUrl = '/sites/MySiteCollection';
serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';

function addWebPart() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);

    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);

    var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' + 
        '<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' + 
        ' xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"' + 
        ' xmlns=\"https://schemas.microsoft.com/WebPart/v2\">' + 
        '<Title>My Web Part</Title><FrameType>Default</FrameType>' + 
        '<Description>Use for formatted text, tables, and images.</Description>' + 
        '<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>' + 
        '<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>' + 
        '<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>' + 
        '<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>' + 
        '<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />' + 
        '<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />' + 
        '<MissingAssembly>Cannot import this Web Part.</MissingAssembly>' + 
        '<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />' + 
        '<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, ' + 
        'PublicKeyToken=94de0004b6e3fcc5</Assembly>' + 
        '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
        '<ContentLink xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" />' + 
        '<Content xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\">' + 
        '<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>' + 
        '<PartStorage xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>';

    var oWebPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
    this.oWebPart = oWebPartDefinition.get_webPart();

    limitedWebPartManager.addWebPart(oWebPart, 'Left', 1);

    clientContext.load(oWebPart);

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

function onQuerySucceeded() {

    alert('Web Part added: ' + oWebPart.get_title());
}

function onQueryFailed(sender, args) {

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

Suppression d'un composant WebPart d'une page

L'exemple suivant montre comment utiliser la méthode DeleteWebPart() (JavaScript: deleteWebPart()) pour supprimer le premier composant WebPart de la page Home.aspx d'un site Web spécifié.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SampleCode
{
    class DeleteWebPart
    {
         static void Main()
        {
            ClientContext oClientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            File oFile = oClientContext.Web.GetFileByServerRelativeUrl("/sites/MySiteCollection/SitePages/Home.aspx ");
            LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            oClientContext.Load(limitedWebPartManager.WebParts);
                        
            oClientContext.ExecuteQuery();

            if (limitedWebPartManager.WebParts.Count == 0)
            {
                throw new Exception("No Web Parts to delete.");
            }

            WebPartDefinition webPartDefinition = limitedWebPartManager.WebParts[0];

            webPartDefinition.DeleteWebPart();
            
            oClientContext.ExecuteQuery();            
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint.Client.WebParts

Namespace Microsoft.SDK.SharePointServices.Samples
    Class DeleteWebPart

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim serverRelativeUrl As String = "/sites/MySiteCollection/SitePages/Home.aspx"

            Dim oClientContext As New ClientContext(siteUrl)
            Dim oFile As File = oClientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl)

            Dim limitedWebPartManager As LimitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared)

            oClientContext.Load(limitedWebPartManager.WebParts)

            oClientContext.ExecuteQuery()

            If limitedWebPartManager.WebParts.Count = 0 Then
                Throw New Exception("No Web Parts to delete.")
            End If

            Dim webPartDefinition As WebPartDefinition = limitedWebPartManager.WebParts(0)

            webPartDefinition.DeleteWebPart()

            oClientContext.ExecuteQuery()

        End Sub
    End Class
End Namespace
siteUrl = '/sites/MySiteCollection';
serverRelativeUrl = '/sites/MySiteCollection/SitePages/Home.aspx';

function retrieveWebParts() {

    this.clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(server2RelativeUrl);

    this.limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    this.collWebPart = limitedWebPartManager.get_webParts();

    clientContext.load(collWebPart);

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

function deleteWebPart () {

    if (!collWebPart.get_count()) {
        alert('No Web Parts to delete.');
    }

    var webPartDefinition = limitedWebPartManager.get_webParts().get_item(0);

    webPartDefinition.deleteWebPart();

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

    alert('Web Part deleted.');
}
function onQueryFailed(sender, args) {

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

Pour des informations et des exemples sur l'utilisation des clients dans le contexte de l'objet Silverlight Microsoft SharePoint Foundation 2010, consultez Utilisation du modèle objet Silverlight.

Voir aussi

Concepts

Vue d'ensemble de la récupération des données

Création d’objet client

Directive du modèle objet client

Tâches courantes de programmation

Composants WebPart dans SharePoint Foundation

Autres ressources

Bibliothèque de classes Client

Bibliothèque de classes ECMAScript