C# 如何将 css 类添加到 ASP.Net 中的更新面板?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1202390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:47:02  来源:igfitidea点击:

How can I add a css class to an updatepanel in ASP.Net?

c#asp.netcss

提问by ErnieStings

How can I add a css class to an updatepanel in the c# code behind file of asp.net

如何将 css 类添加到 asp.net 的 c# 代码隐藏文件中的更新面板

采纳答案by Gavin Miller

As you've seen the update panel doesn't have a css class property. So since it can't be done directly you need a work around; there are two (Grabbed from UpdatePanel and CSS) that can get the behavior you desire.

正如您所见,更新面板没有 css 类属性。所以因为它不能直接完成,所以你需要一个解决方法;有两个(从UpdatePanel 和 CSS 中抓取)可以获得您想要的行为。

One is to surround the update panel with a div:

一种是用div包围更新面板:

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

The other is to apply a css selector based on the update panel's id:

另一种是根据更新面板的 id 应用一个 css 选择器:

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

Yet another way not mentioned in the article is surround the panel in a div and style the update panel based on it rendering as a div:

文章中没有提到的另一种方法是将面板包围在一个 div 中,并根据它呈现为一个 div 来设置更新面板的样式:

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

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

回答by Dan Diplo

An update panel can render as a div or span (depending on mode). Easiest way to achieve what you want is to wrap the UpdatePanel in a standard Panel:

更新面板可以呈现为 div 或 span(取决于模式)。实现您想要的最简单方法是将 UpdatePanel 包装在标准面板中:

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

The you can just do this in codebehind:

您可以在代码隐藏中执行此操作:

Panel1.CssClass = "myCssClass";

You could also use a div, like LFSR Consulting said, and add runat="server"and then change the class attribute. But Panel is a bit easier to work with (a Panel just renders as a div).

您也可以使用 div,如 LFSR Consulting 所说,然后添加runat="server"然后更改类属性。但是 Panel 更容易使用(Panel 只是呈现为一个 div)。

回答by Milox

you can use single class html attribute

您可以使用单类 html 属性

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

回答by rainabba

You could also do as I have and just create a new class that inherits the UpdatePanel. I got the basis for this somewhere else but I don't remember where so I can't credit fully but I only tweaked it for this idea. I'm about to do the same for HTML Attributes (since the .attributes() collection is for css on the UpdatePanel instead of raw HTML attributes as with most other web.ui.controls).

您也可以按照我的方式进行操作,只需创建一个继承 UpdatePanel 的新类。我在其他地方得到了这个基础,但我不记得在哪里,所以我不能完全相信,但我只是为了这个想法调整了它。我即将对 HTML 属性做同样的事情(因为 .attributes() 集合是用于 UpdatePanel 上的 css 而不是像大多数其他 web.ui.controls 那样的原始 HTML 属性)。

UPDATED: I've updated to include some other customization I've made that allow for ANY attribute to be added. Really this duplicates the first customization except that the 1st creates a fairly standard approach where this is completely flexible (thus not standard).

更新:我已更新以包含我所做的一些其他自定义,以允许添加任何属性。实际上这重复了第一个自定义,除了第一个创建了一个相当标准的方法,这是完全灵活的(因此不是标准的)。

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# conversion via http://www.developerfusion.com/:

通过http://www.developerfusion.com/ 进行C# 转换:

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.");
            }
        }

    }


}

回答by krlzlx

HTML

HTML

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

CSS

CSS

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

回答by Tristan

CodeBehind:

代码隐藏:

UpdatePanel panel = new UpdatePanel();

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

HTML Result:

HTML 结果:

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