2009-07-29 17 views
27

¿Cómo puedo agregar una clase css a un panel de actualización en el código C# detrás del archivo de asp.net¿Cómo puedo agregar una clase css a un panel de actualización en ASP.Net?

+0

tal vez usted necesidad de aclarar su pregunta un poco ....no se puede agregar una clase (pura) a un panel de actualización (control) usted agrega controles al panel de actualización – Jaime

+0

¿Qué quiere decir con "clase"? Clase de Css? clase que hereda de System.Web.UI.Control? escriba con algunos datos que desea hacer un seguimiento? –

+5

a css class. el panel de actualización se representa como div, por lo que debería poder asignarse una clase css – ErnieStings

Respuesta

18

Como has visto, el panel de actualización no tiene una propiedad de clase css. Entonces, como no se puede hacer directamente, necesitas un trabajo completo; hay dos (tomados de UpdatePanel and CSS) que pueden obtener el comportamiento que deseas.

Uno es para rodear el panel de actualización con un div:

<div id="foo" style="visibility: hidden; position: absolute"> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    </asp:UpdatePanel> 
</div> 

La otra es aplicar un selector CSS basado en el id del panel de actualización:

<style type="text/css"> 
#<%=UpdatePanel1.ClientID%> { 
    visibility: hidden; 
    position: absolute; 
} 
</style> 

embargo, otra forma no se menciona en el artículo está alrededor del panel en un div y da estilo al panel de actualización en función de su representación como un div:

<style type="text/css"> 
#foo div { 
    visibility: hidden; 
    position: absolute; 
} 
</style> 

<div id="foo"> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    </asp:UpdatePanel> 
</div> 
3

Un panel de actualización puede representarse como div o span (según el modo). La manera más fácil de lograr lo que se desea es envolver el UpdatePanel en un panel estándar:

<asp:Panel ID="Panel1" runat="Server"> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    </asp:UpdatePanel> 
</asp:Panel> 

El simplemente puede hacer esto en código subyacente:

Panel1.CssClass = "myCssClass"; 

También es posible usar un div, como LFSR Consulting dicho, y agregue runat="server" y luego cambie el atributo de la clase. Pero el Panel es un poco más fácil de trabajar (un Panel simplemente lo renderiza como un div).

16

puede utilizar html clase solo atributo

<asp:UpdatePanel ID="UpdatePanel1" runat="server" class="MyCssClass"> 
</asp:UpdatePanel> 
+2

Esto funciona en .NET 4, pero el analizador .NET anterior explota cuando intentas hacer esto con 'System.Web.HttpParseException: Escriba 'System.Web.UI.UpdatePanel' no tiene una propiedad pública llamada 'class'' – bdukes

+8

Esto es porque 'UpdatePanel' no implementa [' IAttributeAccessor'] (http://msdn.microsoft.com/en- us/library/system.web.ui.iattributeaccessor.aspx) en .NET 3.5, pero lo hace en .NET 4 (por lo que no puede agregar programáticamente la 'clase' a través de la propiedad' Attributes', porque eso se agregó en .NET 4, también). – bdukes

3

También puede hacer como yo y simplemente crear una nueva clase que hereda el UpdatePanel. Tengo la base para esto en otro lugar, pero no recuerdo dónde, así que no puedo dar crédito por completo, pero solo lo modifiqué por esta idea. Estoy a punto de hacer lo mismo con los Atributos HTML (ya que la colección .attributes() es para css en el Panel de actualización en lugar de atributos de HTML sin formato como con la mayoría de los otros controles web.ui.).

ACTUALIZADO: He actualizado para incluir algunas otras personalizaciones que he hecho que permiten que se agregue CUALQUIER atributo. Realmente esto duplica la primera personalización, excepto que la primera crea un enfoque bastante estándar donde esto es completamente flexible (por lo tanto no es estándar).

Imports System.ComponentModel 
Imports System.Collections 
Imports System.Web.UI   

Namespace Controls 

    Public Class UpdatePanelCss 
     Inherits UpdatePanel 
     Private _cssClass As String 
     Private _tag As HtmlTextWriterTag = HtmlTextWriterTag.Div 
     Public HtmlAttributes As New HtmlAttributes 

     <DefaultValue("")> _ 
     <Description("Applies a CSS style to the panel.")> _ 
     Public Property CssClass() As String 
      Get 
       Return If(_cssClass, [String].Empty) 
      End Get 
      Set(ByVal value As String) 
       _cssClass = value 
      End Set 
     End Property 

     ' Hide the base class's RenderMode property since we don't use it 
     <Browsable(False)> _ 
     <EditorBrowsable(EditorBrowsableState.Never)> _ 
     <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ 
     Public Shadows Property RenderMode() As UpdatePanelRenderMode 
      Get 
       Return MyBase.RenderMode 
      End Get 
      Set(ByVal value As UpdatePanelRenderMode) 
       MyBase.RenderMode = value 
      End Set 
     End Property 

     <DefaultValue(HtmlTextWriterTag.Div)> _ 
     <Description("The tag to render for the panel.")> _ 
     Public Property Tag() As HtmlTextWriterTag 
      Get 
       Return _tag 
      End Get 
      Set(ByVal value As HtmlTextWriterTag) 
       _tag = value 
      End Set 
     End Property 

     Protected Overrides Sub RenderChildren(ByVal writer As HtmlTextWriter) 
      If IsInPartialRendering Then 
       ' If the UpdatePanel is rendering in "partial" mode that means 
       ' it's the top-level UpdatePanel in this part of the page, so 
       ' it doesn't render its outer tag. We just delegate to the base 
       ' class to do all the work. 
       MyBase.RenderChildren(writer) 
      Else 
       ' If we're rendering in normal HTML mode we do all the new custom 
       ' rendering. We then go render our children, which is what the 
       ' normal control's behavior is. 
       writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID) 
       If CssClass.Length > 0 Then 
        writer.AddAttribute(HtmlTextWriterAttribute.[Class], CssClass) 
       End If 
       If HtmlAttributes.Count > 0 Then 
        For Each ha As HtmlAttribute In HtmlAttributes 
         writer.AddAttribute(ha.AttrName, ha.AttrVal) 
        Next 
       End If 
       writer.RenderBeginTag(Tag) 
       For Each child As Control In Controls 
        child.RenderControl(writer) 
       Next 
       writer.RenderEndTag() 
      End If 
     End Sub 

    End Class 

    Public Class HtmlAttribute 
     Private PAttrName As String 
     Private PAttrVal As String 

     Public Sub New(AttrName As String, AttrVal As String) 
      PAttrName = AttrName 
      PAttrVal = AttrVal 
     End Sub 

     Public Property AttrName() As String 
      Get 
       Return PAttrName 
      End Get 
      Set(value As String) 
       PAttrName = value 
      End Set 
     End Property 

     Public Property AttrVal() As String 
      Get 
       Return PAttrVal 
      End Get 
      Set(value As String) 
       PAttrVal = value 
      End Set 
     End Property 

    End Class 


    Public Class HtmlAttributes 
     Inherits CollectionBase 

     Public ReadOnly Property Count() As Integer 
      Get 
       Return List.Count 
      End Get 
     End Property 

     Default Public Property Item(ByVal index As Integer) As HtmlAttribute 
      Get 
       Return CType(List.Item(index), HtmlAttribute) 
      End Get 
      Set(ByVal Value As HtmlAttribute) 
       List.Item(index) = Value 
      End Set 
     End Property 

     Public Function Add(ByVal item As HtmlAttribute) As Integer 
      Return List.Add(item) 
     End Function 

     Public Sub Remove(ByVal index As Integer) 
      If index < List.Count AndAlso List.Item(index) IsNot Nothing Then 
       List.RemoveAt(index) 
      Else 
       Throw New Exception(String.Concat("Index(", index.ToString, ") is not valid. List only has ", List.Count.ToString, " items.")) 
      End If 
     End Sub 

     Public Sub Remove(ByRef hAttribute As HtmlAttribute) 
      If List.Count > 0 AndAlso List.IndexOf(hAttribute) >= 0 Then 
       List.Remove(hAttribute) 
      Else 
       Throw New Exception("Object does not exist in collection.") 
      End If 
     End Sub 

    End Class 


End Namespace 

C# conversión a través de http://www.developerfusion.com/:

using Microsoft.VisualBasic; 
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Data; 
using System.Diagnostics; 
using System.ComponentModel; 
using System.Web.UI; 

namespace Controls 
{ 

    public class UpdatePanelCss : UpdatePanel 
    { 
     private string _cssClass; 
     private HtmlTextWriterTag _tag = HtmlTextWriterTag.Div; 

     public HtmlAttributes HtmlAttributes = new HtmlAttributes(); 
     [DefaultValue("")] 
     [Description("Applies a CSS style to the panel.")] 
     public string CssClass { 
      get { return _cssClass ?? String.Empty; } 
      set { _cssClass = value; } 
     } 

     // Hide the base class's RenderMode property since we don't use it 
     [Browsable(false)] 
     [EditorBrowsable(EditorBrowsableState.Never)] 
     [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] 
     public new UpdatePanelRenderMode RenderMode { 
      get { return base.RenderMode; } 
      set { base.RenderMode = value; } 
     } 

     [DefaultValue(HtmlTextWriterTag.Div)] 
     [Description("The tag to render for the panel.")] 
     public HtmlTextWriterTag Tag { 
      get { return _tag; } 
      set { _tag = value; } 
     } 

     protected override void RenderChildren(HtmlTextWriter writer) 
     { 
      if (IsInPartialRendering) { 
       // If the UpdatePanel is rendering in "partial" mode that means 
       // it's the top-level UpdatePanel in this part of the page, so 
       // it doesn't render its outer tag. We just delegate to the base 
       // class to do all the work. 
       base.RenderChildren(writer); 
      } else { 
       // If we're rendering in normal HTML mode we do all the new custom 
       // rendering. We then go render our children, which is what the 
       // normal control's behavior is. 
       writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); 
       if (CssClass.Length > 0) { 
        writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); 
       } 
       if (HtmlAttributes.Count > 0) { 
        foreach (HtmlAttribute ha in HtmlAttributes) { 
         writer.AddAttribute(ha.AttrName, ha.AttrVal); 
        } 
       } 
       writer.RenderBeginTag(Tag); 
       foreach (Control child in Controls) { 
        child.RenderControl(writer); 
       } 
       writer.RenderEndTag(); 
      } 
     } 

    } 

    public class HtmlAttribute 
    { 
     private string PAttrName; 

     private string PAttrVal; 
     public HtmlAttribute(string AttrName, string AttrVal) 
     { 
      PAttrName = AttrName; 
      PAttrVal = AttrVal; 
     } 

     public string AttrName { 
      get { return PAttrName; } 
      set { PAttrName = value; } 
     } 

     public string AttrVal { 
      get { return PAttrVal; } 
      set { PAttrVal = value; } 
     } 

    } 


    public class HtmlAttributes : CollectionBase 
    { 

     public int Count { 
      get { return List.Count; } 
     } 

     public HtmlAttribute this[int index] { 
      get { return (HtmlAttribute)List[index]; } 
      set { List[index] = value; } 
     } 

     public int Add(HtmlAttribute item) 
     { 
      return List.Add(item); 
     } 

     public void Remove(int index) 
     { 
      if (index < List.Count && List[index] != null) { 
       List.RemoveAt(index); 
      } else { 
       throw new Exception(string.Concat("Index(", index.ToString(), ") is not valid. List only has ", List.Count.ToString(), " items.")); 
      } 
     } 

     public void Remove(ref HtmlAttribute hAttribute) 
     { 
      if (List.Count > 0 && List.IndexOf(hAttribute) >= 0) { 
       List.Remove(hAttribute); 
      } else { 
       throw new Exception("Object does not exist in collection."); 
      } 
     } 

    } 


} 
+1

Aunque esta respuesta es útil, la pregunta se hizo con la etiqueta C#, no con VB.NET. –

+0

Todo está bien. Volví a subir tu respuesta, no es necesario que te enojes. –

+0

Gracias Ed. Borrando mi último. – rainabba

0

HTML

<asp:UpdatePanel ID="UpdatePanel1" runat="server"></asp:UpdatePanel> 

CSS

<style type="text/css"> 
    #UpdatePanel1 { position: relative; } 
</style> 
+0

Por favor explique el voto a favor. – krlzlx

1

CodeBehind:

UpdatePanel panel = new UpdatePanel(); 

panel.Attributes.Add("class","your-css-class"); 

HTML Resultado:

<div id="..." class="your-css-class"></div> 
Cuestiones relacionadas