【问题标题】:Setting title tags using asp.net使用 asp.net 设置标题标签
【发布时间】:2016-07-24 04:42:04
【问题描述】:

我正在尝试以编程方式设置一组元数据。

我在我的 asp.net 母版页上有以下设置:

<asp:ContentPlaceHolder ID="MetaTags" runat="server">
    <meta name="description" content="">
</asp:ContentPlaceHolder>

然后我将其放在单独的页面上:

<asp:Content runat="server" ContentPlaceHolderID="MetaTags">    
<title runat="server" id="pageTitle"></title>
<meta runat="server" id="pageDescription" name="description"/>  
<meta runat="server" id="pageKeywords" name="keywords" />    
</asp:Content>

这在 C# 代码中:

    pageTitle.InnerText = "TITLE";
    pageDescription.InnerText = "DESC";
    pageKeywords.InnerText = "KEY";

在页面上生成这个:

<title id="ctl00_MetaTags_pageTitle">TITLE</title>
<meta id="ctl00_MetaTags_pageDescription" name="description">DESC</meta>  
<meta id="ctl00_MetaTags_pageKeywords" name="keywords">KEY</meta> 

我这样做是因为我的理解是因为我在使用:

<asp:ContentPlaceHolder ID="MetaTags" runat="server">

我不能在单个页面上使用 &lt;head&gt; 标记 - 因为它会导致重复的标题标记?

我尝试使用:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="###"  MasterPageFile="#####" Title = ""%>

在 C# 中 Page.Title = "Title"

但这并没有显示任何内容。

另外Master.Page.Title = "Title";

但这也不起作用。

所以,我的问题分两部分;

1.有没有人知道另一种以编程方式将元数据添加到页面的方法。

2.如果我这样做,并且元数据具有 id,例如:

<title id="ctl00_MetaTags_pageTitle">TITLE</title>

这是否会使标题标签无效。

【问题讨论】:

    标签: c# html asp.net seo


    【解决方案1】:

    1.有没有人知道另一种以编程方式将元数据添加到页面的方法。

    您可以通过简单地创建一个Placeholder 然后在您的代码隐藏中构建您的个人元标记并将它们添加到其中来完成此操作:

    <head runat="server">
        <title>Your Example Page</title>
        <!-- Add your Meta tags into this container -->
        <asp:PlaceHolder ID="Meta" runat="server" />
    </head>
    

    然后在您的代码隐藏中,您可以将它们构建为HtmlMeta 控件并按预期插入它们:

    // Build each of your meta tags and add them
    var tags = new List<HtmlMeta>() {
         new HtmlMeta() { Name = "description",Content = "Your Description Here" },
         new HtmlMeta() { Name = "keywords", Content = "a,b,c,d" },
         new HtmlMeta() { Name = "robots", Content = "index,follow" }
    };
    
    // Add each of them to your placeholder
    foreach(var tag in tags)
    {
         Meta.Controls.Add(tag);
    }
    

    这将在您的&lt;head&gt; 部分呈现如下:

    <head>
        <title>Your Example Page</title>
        <meta name="description" content="Your Description Here">
        <meta name="keywords" content="a,b,c,d">
        <meta name="robots" content="index,follow">
    </head>
    

    您可以根据需要轻松调整。

    2.如果我这样做,并且元数据具有 id 的... 这会使标题标签无效吗?

    IIRC,我认为这不会对实际的&lt;meta&gt; 标签按预期工作产生任何不利影响,尽管the spec doesn't specify it as a valid tag。不过一般情况下,您应该尽可能避免添加它们。

    【讨论】:

    • meta name="keywords" meta http-equiv="X-UA-Compatible" meta name="twitter:title" meta property="og:site_name" ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多