IPersonalizable.IsDirty Propiedad

Definición

Obtiene un valor que indica si han cambiado los datos personalizados que administra un control.

public:
 property bool IsDirty { bool get(); };
public bool IsDirty { get; }
member this.IsDirty : bool
Public ReadOnly Property IsDirty As Boolean

Valor de propiedad

true si han cambiado los datos personalizados administrados con la interfaz IPersonalizable; de lo contrario, false.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de la IsDirty propiedad . La primera parte del ejemplo es la página web que hospeda un WebPart control .

<%@ Page Language="C#"  %>
<%@ Register TagPrefix="dict" 
    namespace="Samples.AspNet.CS.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IPersonalizable</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:WebPartManager ID="mgr" runat="server" />
    <div>
    <asp:WebPartZone ID="WebPartZone1" runat="server">
      <ZoneTemplate>
        <dict:urllistwebpart id="listwp1" runat="server"
          title="URL List WebPart" />
      </ZoneTemplate>
    </asp:WebPartZone>
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB"  %>
<%@ Register TagPrefix="dict" 
    namespace="Samples.AspNet.VB.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IPersonalizable</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:WebPartManager ID="mgr" runat="server" />
    <div>
    <asp:WebPartZone ID="WebPartZone1" runat="server">
      <ZoneTemplate>
        <dict:urllistwebpart id="listwp1" runat="server"
          title="URL List WebPart" />
      </ZoneTemplate>
    </asp:WebPartZone>
    </div>
    </form>
</body>
</html>

La segunda parte del ejemplo es el código del control personalizado WebPart denominado UrlListWebPart. Este archivo debe colocarse en el directorio App_Code para ejecutar el ejemplo. Tenga en cuenta que el código fuente implementa la IsDirty propiedad .

namespace Samples.AspNet.CS.Controls
{

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Web;
    using System.Web.UI;
    using System.Security.Permissions;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;

    [AspNetHostingPermission(SecurityAction.Demand,
      Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand,
      Level = AspNetHostingPermissionLevel.Minimal)]
    public class UrlListWebPart : WebPart, IPersonalizable
    {
        private ArrayList _sharedUrls;
        private ArrayList _userUrls;
        private bool _listDirty;

        private TextBox _nameTextBox;
        private TextBox _urlTextBox;
        private Button _addButton;
        private BulletedList _list;

        protected override void CreateChildControls()
        {
            Label nameLabel = new Label();
            Label urlLabel = new Label();
            LiteralControl breakLiteral1 = new LiteralControl("<br />");
            LiteralControl breakLiteral2 = new LiteralControl("<br />");
            LiteralControl breakLiteral3 = new LiteralControl("<br />");

            _nameTextBox = new TextBox();
            _urlTextBox = new TextBox();
            _addButton = new Button();
            _list = new BulletedList();

            nameLabel.Text = "Name: ";
            urlLabel.Text = "URL: ";
            _nameTextBox.ID = "nameTextBox";
            _urlTextBox.ID = "urlTextBox";
            _addButton.Text = "Add";
            _addButton.ID = "addButton";
            _addButton.Click += new EventHandler(this.OnClickAddButton);
            _list.DisplayMode = BulletedListDisplayMode.HyperLink;
            _list.ID = "list";

            Controls.Add(nameLabel);
            Controls.Add(_nameTextBox);
            Controls.Add(breakLiteral1);

            Controls.Add(urlLabel);
            Controls.Add(_urlTextBox);
            Controls.Add(breakLiteral2);

            Controls.Add(_addButton);
            Controls.Add(breakLiteral3);

            Controls.Add(_list);
        }

        private void OnClickAddButton(object sender, EventArgs e)
        {
            string name = _nameTextBox.Text.Trim();
            string url = _urlTextBox.Text.Trim();

            Pair p = new Pair(name, url);
            if (WebPartManager.Personalization.Scope == PersonalizationScope.Shared)
            {
                _sharedUrls ??= new ArrayList();
                _sharedUrls.Add(p);
            }
            else
            {
                _userUrls ??= new ArrayList();
                _userUrls.Add(p);
            }

            OnUrlAdded();
        }

        protected virtual void OnUrlAdded()
        {
            _listDirty = true;
            ChildControlsCreated = false;
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (_sharedUrls != null)
            {
                foreach (Pair p in _sharedUrls)
                {
                    _list.Items.Add(new ListItem((string)p.First, (string)p.Second));
                }
            }
            if (_userUrls != null)
            {
                foreach (Pair p in _userUrls)
                {
                    _list.Items.Add(new ListItem((string)p.First, (string)p.Second));
                }
            }

            base.RenderContents(writer);
        }

        public virtual bool IsDirty
        {
            get
            {
                return _listDirty;
            }
        }
        public new virtual void Load(PersonalizationDictionary state)
        {
            if (state != null)
            {
                PersonalizationEntry sharedUrlsEntry = state["sharedUrls"];
                if (sharedUrlsEntry != null)
                {
                    _sharedUrls = (ArrayList)sharedUrlsEntry.Value;
                }

                PersonalizationEntry userUrlsEntry = state["userUrls"];
                if (userUrlsEntry != null)
                {
                    _userUrls = (ArrayList)userUrlsEntry.Value;
                }
            }
        }

        public virtual void Save(PersonalizationDictionary state)
        {
            if ((_sharedUrls != null) && (_sharedUrls.Count != 0))
            {
                state["sharedUrls"] = new PersonalizationEntry(_sharedUrls, PersonalizationScope.Shared);
            }
            if ((_userUrls != null) && (_userUrls.Count != 0))
            {
                state["userUrls"] = new PersonalizationEntry(_userUrls, PersonalizationScope.User);
            }
        }
    }
}

Imports System.Collections
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.Web
Imports System.Web.UI
Imports System.Security.Permissions
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class UrlListWebPart
      Inherits WebPart
      Implements IPersonalizable
      Private _sharedUrls As ArrayList
      Private _userUrls As ArrayList
      Private _listDirty As Boolean

      Private _nameTextBox As TextBox
      Private _urlTextBox As TextBox
      Private _addButton As Button
      Private _list As BulletedList


      Protected Overrides Sub CreateChildControls()
          Dim nameLabel As New Label()
          Dim urlLabel As New Label()
          Dim breakLiteral1 As New LiteralControl("<br />")
          Dim breakLiteral2 As New LiteralControl("<br />")
          Dim breakLiteral3 As New LiteralControl("<br />")

          _nameTextBox = New TextBox()
          _urlTextBox = New TextBox()
          _addButton = New Button()
          _list = New BulletedList()

          nameLabel.Text = "Name: "
          urlLabel.Text = "URL: "
          _nameTextBox.ID = "nameTextBox"
          _urlTextBox.ID = "urlTextBox"
          _addButton.Text = "Add"
          _addButton.ID = "addButton"
          AddHandler _addButton.Click, AddressOf Me.OnClickAddButton
          _list.DisplayMode = BulletedListDisplayMode.HyperLink
          _list.ID = "list"

          Controls.Add(nameLabel)
          Controls.Add(_nameTextBox)
          Controls.Add(breakLiteral1)

          Controls.Add(urlLabel)
          Controls.Add(_urlTextBox)
          Controls.Add(breakLiteral2)

          Controls.Add(_addButton)
          Controls.Add(breakLiteral3)

          Controls.Add(_list)

      End Sub


      Private Sub OnClickAddButton(ByVal sender As Object, ByVal e As EventArgs)
          Dim name As String = _nameTextBox.Text.Trim()
          Dim url As String = _urlTextBox.Text.Trim()

          Dim p As New Pair(name, url)
          If WebPartManager.Personalization.Scope = PersonalizationScope.Shared Then
              If _sharedUrls Is Nothing Then
                  _sharedUrls = New ArrayList()
              End If
              _sharedUrls.Add(p)
          Else
              If _userUrls Is Nothing Then
                  _userUrls = New ArrayList()
              End If
              _userUrls.Add(p)
          End If

          OnUrlAdded()

      End Sub


      Protected Overridable Sub OnUrlAdded()
          _listDirty = True
          ChildControlsCreated = False

      End Sub


      Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
          If Not (_sharedUrls Is Nothing) Then
              Dim p As Pair
              For Each p In _sharedUrls
                  _list.Items.Add(New ListItem(CStr(p.First), CStr(p.Second)))
              Next p
          End If
          If Not (_userUrls Is Nothing) Then
              Dim p As Pair
              For Each p In _userUrls
                  _list.Items.Add(New ListItem(CStr(p.First), CStr(p.Second)))
              Next p
          End If

          MyBase.RenderContents(writer)

      End Sub


      Public Overridable ReadOnly Property IsDirty() As Boolean _
        Implements IPersonalizable.IsDirty
          Get
              Return _listDirty
          End Get
      End Property

      Public Overridable Shadows Sub Load(ByVal state As PersonalizationDictionary) _
        Implements IPersonalizable.Load
          If Not (state Is Nothing) Then
              Dim sharedUrlsEntry As PersonalizationEntry = state("sharedUrls")
              If Not (sharedUrlsEntry Is Nothing) Then
                  _sharedUrls = CType(sharedUrlsEntry.Value, ArrayList)
              End If

              Dim userUrlsEntry As PersonalizationEntry = state("userUrls")
              If Not (userUrlsEntry Is Nothing) Then
                  _userUrls = CType(userUrlsEntry.Value, ArrayList)
              End If
          End If

      End Sub

      Public Overridable Sub Save(ByVal state As PersonalizationDictionary) _
        Implements IPersonalizable.Save
          If Not (_sharedUrls Is Nothing) AndAlso _sharedUrls.Count <> 0 Then
              state("sharedUrls") = New PersonalizationEntry(_sharedUrls, PersonalizationScope.Shared)
          End If
          If Not (_userUrls Is Nothing) AndAlso _userUrls.Count <> 0 Then
              state("userUrls") = New PersonalizationEntry(_userUrls, PersonalizationScope.User)
          End If

      End Sub
  End Class


End Namespace

Cargue la página en un explorador. Escriba un nombre para representar una dirección URL y agregue una dirección URL real a partir http://de y haga clic en el botón Agregar para agregar la dirección URL.

Comentarios

Cuando los datos administrados por un control han cambiado, el control se considera "sucio". Un control debe devolver true si los datos personalizados que administra a través de la IPersonalizable interfaz han cambiado. Si un control devuelve true de esta propiedad, se llama a la implementación del método de interfaz del control durante la extracción de Save valores de propiedad.

Nota:

La infraestructura de personalización comprueba automáticamente esta propiedad durante las últimas fases del procesamiento de una solicitud POST. Sin embargo, para las solicitudes GET, no se comprueba el valor devuelto de la IsDirty propiedad . Otro evento tiene que haber provocado que el control se considere "sucio" para cualquier estado de control,no solo los datos administrados por IPersonalizable--se guardarán. Si un control se puede marcar como "sucio" durante una solicitud GET, o si la infraestructura de personalización en algunas condiciones de límite muy específicas considera un control "sucio" durante una solicitud GET, Save siempre se llamará a .

Un control puede hacer referencia a su control asociado WebPartManager y comprobar la Scope propiedad para determinar el ámbito actual. El estado "sucio" de los datos personalizados de un control debe ser adecuado para el ámbito actual.

Se aplica a