Compartir a través de


Procedimiento para trabajar con elementos web en una página

Última modificación: sábado, 30 de abril de 2011

Hace referencia a: SharePoint Foundation 2010

En este artículo
Actualización del título de un elemento web
Adición de un elemento web a una página
Eliminación de un elemento web de una página

Disponible en SharePoint Online

Use las clases en el espacio de nombres Microsoft.SharePoint.Client.WebParts (JavaScript: SP.WebParts) para trabajar con elementos web en todo el modelo de objetos cliente. La clase LimitedWebPartManager (JavaScript: LimitedWebPartManager) permite obtener acceso a la colección de elementos web en una página de SharePoint con un ámbito compartido o personal mediante la propiedad WebParts (JavaScript: webParts).

Actualización del título de un elemento web

E el ejemplo siguiente se cambia el título del segundo elemento web en la colección de elementos web de la página Default.aspx del sitio web especificado. El ejemplo usa una expresión de consulta para devolver únicamente el título de cada elemento web y llama al método SaveWebPartChanges() (JavaScript: saveWebPartChanges()) para guardar los cambios. El método ExecuteQuery() o ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) se llama dos veces, en primer lugar para devolver la colección de elementos web a fin de que el código pueda comprobar que hay elementos web en la página y en segundo lugar para realizar los cambios en la base de datos.

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

Adición de un elemento web a una página

En el ejemplo siguiente se agrega un elemento web editor de contenido personalizado como segundo elemento web, en orden, dentro del área izquierda de la página Default.aspx para un sitio web especificado. El ejemplo define el XML para el elemento web, le pasa esta cadena al método ImportWebPart(String) (JavaScript: importWebPart(webPartXml)) y, a continuación, llama al método AddWebPart(WebPart, String, Int32) (JavaScript: addWebPart(webPart, zoneId, zoneIndex)) para agregar el elemento web a la página.

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

Eliminación de un elemento web de una página

En el ejemplo siguiente se muestra cómo usar el método DeleteWebPart() (JavaScript: deleteWebPart()) para eliminar el primer elemento web de la página Home.aspx de un sitio web especificado.

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

Para obtener más información y ejemplos acerca de cómo trabajar con objetos cliente dentro del contexto del modelo de objetos Silverlight de Microsoft SharePoint Foundation 2010, vea Uso del modelo de objetos Silverlight.

Vea también

Conceptos

Introducción a la recuperación de datos

Creación de objetos cliente

Instrucciones del modelo de objetos cliente

Tareas comunes de programación

Elementos web en SharePoint Foundation

Otros recursos

Biblioteca de clases de cliente

Biblioteca de clases de ECMAScript