动态更改元标记时出错

时间:2011-07-20 12:44:30

标签: c# asp.net html master-pages meta-tags

我有一个母版页,其中定义了元标记名称和描述。如果我这样做,我无法使用头runat="server",因为我遇到了一些URL路由问题。

我想动态更改网站中某个子页面的元描述。我试过这个:

HtmlHead headTag = (HtmlHead)this.Header;
HtmlMeta pageMetaTag = new HtmlMeta();
pageMetaTag.Name = "Description";
pageMetaTag.Content = "Test";
headTag.Controls.Add(pageMetaTag);

但我在添加行上收到错误,说:

Object reference not set to an instance of an object.

在头部内容中保留子页面的<head runat="server"></head>时,页面会运行,但不会覆盖元描述标记。元描述与主页的描述相同...... 请帮我解决这个问题......

使用:VS2010中的ASP.NET 4

更新(子页面相似):

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Profile.aspx.cs" Inherits="Profile"%>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajax" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <head runat="server"></head>
    <style type="text/css" runat="server"> 
                   .lnkbtn
                    {
                        color: #000080;
                        cursor:pointer;
                    }
                    .lnkbtn:hover
                    {
                        color: #800000;
                        text-decoration: underline;
                    }
    </style>
<link rel="stylesheet" type="text/css" href='<%= ResolveUrl("~/css/back.css") %>'/>
    <script type="text/javascript" src='<%= ResolveUrl("~/css/front.js") %>'></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
     // contains
     // update panel
     // webpartmanager
     // webpartzones
</asp:Content>

更新(头部嵌套在头部标签内)

使用Page.MetaDescription = "Hi How are you";时,以下是页面来源:

<head>
    <titleMaster Page Title</title>
    <meta name="Keywords" content="Master page keywords" />
    <meta name="description" content="Master page meta description." />
    .
    .
    .
     <head><title>Child page Title</title>
     <meta name="description" content="Hi How are you" /></head>

    .
    .
    .
</head>

3 个答案:

答案 0 :(得分:0)

试试这个

HtmlMeta keywords = new HtmlMeta();
keywords.Name = "keywords";
keywords.Content = "google, yahoo";
Header.Controls.Add(keywords);

确保标记

<head runat="server">

答案 1 :(得分:0)

我认为你需要

<head runat="server">

Header.Controls.Add(pageMetaTag);

至少我使用这个确切的代码并且它可以正常工作

        HtmlMeta siteVerificationMeta = new HtmlMeta();
        siteVerificationMeta.Name = "xxxx";
        siteVerificationMeta.Content = "xxxx";
        Header.Controls.AddAt(0, siteVerificationMeta);

编辑:我认为这就是您所需要的,您正在添加新标题,您需要编辑如下

请注意注释掉的行!!

     //HtmlHead headTag = (HtmlHead)this.Header;
     HtmlMeta pageMetaTag = new HtmlMeta();
     pageMetaTag.Name = "Description";
     pageMetaTag.Content = "Test";
     Header.Controls.Add(pageMetaTag);

答案 2 :(得分:0)

在Asp.net 4.0中,你可以这样做:

protected void Page_Load(object sender, EventArgs e)
{

    Page.MetaDescription = "My page - a great page indeed";
    Page.MetaKeywords = "keyword1, two, three";
  }