使用ASP.Net 2.0,您可以使用 Title 属性更改页面标题:

Page.Title = "New Title";

但是由于在ASP.Net 1.1中 Page 类中没有 Title 属性,如何从代码隐藏中更改页面标题?

有帮助吗?

解决方案

使用ASP.Net 1.1,首先必须在标题标记上设置 runat 属性:

<title id="PageTitle" runat="server">WebForm1</title>

然后从后面的代码:

C#

// We need this name space to use HtmlGenericControl
using System.Web.UI.HtmlControls;

namespace TestWebApp
{

      public class WebForm1 : System.Web.UI.Page
      {
            // Variable declaration and instantiation
            protected HtmlGenericControl PageTitle = new HtmlGenericControl();

            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Set new page title
                  PageTitle.InnerText = "New Page Title";
            }
      }
}

结果


<强> VB

Imports System.Web.UI.HtmlControls

Namespace TestWebApp

    Public Class WebForm1
        Inherits System.Web.UI.Page

        Protected PageTitle As HtmlGenericControl = New HtmlGenericControl()

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

            PageTitle.InnerText = "New Page Title"
        End Sub

...

    End Class
End Namespace

其他提示

Andreas Grech的答案在从具有TITLE标记的ASPX页面后面的代码运行时非常有效。

但是如果需要从ASPX页面运行的 Web用户控件更新TITLE标记呢?上述操作会导致错误(因为Web用户控件无法看到PageTitle)。

因此,对于Web用户控件,请按照Grech的解决方案进行操作,但请进行以下调整:

1)不要在Page_Load之前声明PageTitle控件。代替:

2)在Page_Load中声明它如下:

Dim PageTitle as HtmlGenericControl = Page.FindControl(&quot; PageTitle&quot;)

然后设置值。

这里的要点是,如果你在主页中设置标题

<head><title>Master Title</title></head>

在代码端添加标题的代码无效。即使一切正确

Page.Title="Page Title"

上面这个没效果。您必须从母版页中删除标题。之后不需要额外的代码。只需在Page_Load

中添加以下代码 <*>

它会起作用

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top