Freigeben über


Gewusst wie: Verwenden von Webparts auf einer Seite

Letzte Änderung: Samstag, 30. April 2011

Gilt für: SharePoint Foundation 2010

Inhalt dieses Artikels
Aktualisieren des Titels eines Webparts
Hinzufügen eines Webparts zu einer Seite
Löschen eines Webparts von einer Seite

Verfügbar in SharePoint Online

Verwenden Sie Klassen im Microsoft.SharePoint.Client.WebParts-Namespace (JavaScript: SP.WebParts), um Webparts über das Clientobjektmodell zu verwenden. Mithilfe der LimitedWebPartManager-Klasse (JavaScript: LimitedWebPartManager) können Sie auf die Auflistung der Webparts auf einer SharePoint-Seite innerhalb eines freigegebenen oder persönlichen Bereichs über die WebParts-Eigenschaft (JavaScript: webParts) zugreifen.

Aktualisieren des Titels eines Webparts

Im folgenden Beispiel wird der Titel des zweiten Webparts in der Auflistung der Webparts auf der Seite Default.aspx der angegebenen Website geändert. Im Beispiel wird ein LINQ-Abfrageausdruck verwendet, um nur den Titel jedes Webparts zurückzugeben, und die SaveWebPartChanges()-Methode (JavaScript: saveWebPartChanges()) wird zum Speichern von Änderungen aufgerufen. Die ExecuteQuery()- oder ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler)-Methode (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) wird zweimal aufgerufen, zuerst zum Zurückgeben der Auflistung von Webparts, sodass der Code das Vorhandensein von Webparts auf der Seite überprüfen kann, und zweitens, um die Änderungen in der Datenbank zu übernehmen.

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());
}

Hinzufügen eines Webparts zu einer Seite

Im folgenden Beispiel wird ein benutzerdefiniertes Inhalts-Editor-Webpart als zweites Webpart in der Reihenfolge hinzugefügt, und zwar in der linken Zone der Seite Default.aspx für eine angegebene Website. In dem Beispiel wird der XML-Code für das Webpart definiert, diese Zeichenfolge an die ImportWebPart(String)-Methode (JavaScript: importWebPart(webPartXml)) übergeben und anschließend die AddWebPart(WebPart, String, Int32)-Methode (JavaScript: addWebPart(webPart, zoneId, zoneIndex)) aufgerufen, um das Webpart der Seite hinzuzufügen.

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());
}

Löschen eines Webparts von einer Seite

Im folgenden Beispiel wird die Verwendung der DeleteWebPart()-Methode (JavaScript: deleteWebPart()) zum Löschen des ersten Webparts von der Seite Home.aspx einer angegebenen Website gezeigt.

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());
}

Informationen und Beispiele zum Verwenden von Clientobjekten im Kontext des Microsoft SharePoint Foundation 2010 Silverlight-Objektmodells finden Sie unter Verwenden des Silverlight-Objektmodells.

Siehe auch

Konzepte

Übersicht über den Datenabruf

Erstellen von Clientobjekten

Richtlinien für das Clientobjektmodell

Allgemeine Programmieraufgaben

Webparts in SharePoint Foundation

Weitere Ressourcen

Clientklassenbibliothek

ECMAScript-Klassenbibliothek