Page.Header.Controls.Add增加样式到正文而不是head

时间:2018-07-11 08:51:40

标签: c# asp.net

Page.Header.Controls.Add方法在 asp.net 4 中 在body标签中添加样式和脚本,而不是在head标签中添加

可以使用另一种方法在head标签中添加样式和脚本吗?

  

Asp.Net 4

1 个答案:

答案 0 :(得分:0)

有很多方法可以实现这一点,下面我将解释其中的两个

  1. 在头部使用文字控制
  2. 使用HtmlGenericControl类

I。在头部使用文字控制

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:Literal ID="litHeader" runat="server" />
</head>
<body>
    <form id="form1" runat="server">
        <h1>
            Hello World
        </h1>
    </form>
</body>
</html>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace tempApp
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            litHeader.Text = @"
                <style>h1 { color: red; }</style>
                <script>alert('Hello World')</script>
            ";            
        }
    }
}

在此过程中,我在“ head”部分中做了一个文字控件,然后将我的样式和脚本内容从页面加载后的代码传递给了

II。使用HtmlGenericControl类

WebForm2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="tempApp.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <h1>
            Hello World
        </h1>
    </form>
</body>
</html>

WebForm2.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace tempApp
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var styleControl = new HtmlGenericControl();

            styleControl.TagName = "style";
            styleControl.Attributes.Add("type", "text/css");
            styleControl.InnerHtml = "h1 { color: red; }";

            Page.Header.Controls.Add(styleControl);

            var scriptControl = new HtmlGenericControl();

            scriptControl.TagName = "script";
            scriptControl.Attributes.Add("type", "text/javascript");
            scriptControl.InnerHtml = "alert('Hello World')";

            Page.Header.Controls.Add(scriptControl);
        }
    }
}

在此,我使用了HtmlGenericControl类,该类在使用System.Web.UI.HtmlControls命名空间时使用,我可以创建HTML通用控件,以后再将其添加到页面上。

仍然有很多方法可以实现这一目标。希望对您有帮助

相关问题