【问题标题】:programmatically changing meta description in c#在 C# 中以编程方式更改元描述
【发布时间】:2015-04-09 01:12:14
【问题描述】:

我在页面中有一个元描述标签,我正在像这样以编程方式更改元描述标签的内容

 <meta name="description" content=<%=getmeta()%>  />

getmeta 函数如下

   public string getmeta()
{
    return "this is a meta description's content";

}

当我的页面呈现时,它会呈现像这样无意义的元元素

<meta name="description" content="this" is="" a="" meta="" description's="" content="" >

这是什么原因,我错过了什么?

【问题讨论】:

  • 真的编译了吗?在 getmeta 函数的 return 语句末尾有额外的“)”。
  • 这里的一切都被否决了!即使是正确的答案!! :)
  • @DaveBecker 哪些答案是正确的?
  • 我也在连接 Request.Cookie 值。现在它给了我 content="这是元描述的内容" edmonton,alberta"="。我像这样连接 +HttpUtility.UrlDecode(Request.Cookies["pc"].Value).ToString().Replace(" ","")
  • 只需使用您的原始代码,但将content=&lt;%=getmeta()%&gt; 替换为content="&lt;%=getmeta()%&gt;"(注意额外的双引号)

标签: c# html asp.net .net


【解决方案1】:

首先,您的代码无法编译,因为您的方法末尾有一个额外的 ')':

return "this is a meta description's content");

但是,为了回答您的问题,元标记的内容应该放在双引号之间才能起作用。

我确实建议您调整您的方法以返回包含双引号的字符串,但这需要转义您的双引号字符。

如果您像下面这样修改您的方法,它应该可以工作(经过测试和验证):

public string getmeta()
{
    return "\"this is a meta description's content\"";
}

HTML 中的输出将是:

<meta name="description" content="this is a meta description's content"  />

【讨论】:

  • 你为什么不把双引号放在标记中而不是乱用字符串?
  • 这只是我个人的工作方式。我不太喜欢这样,因此我将它们添加到字符串本身中。
【解决方案2】:

最好的方法是

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.Header.Controls.Add(new LiteralControl(@"<meta name='description' content='this is a meta description's content'  />"));
}

或者另一种方式是-

-将 PlaceHoled 放入您的 .aspx header 部分。

&lt;asp:PlaceHolder id="MetaPlaceHolder" runat="server" /&gt;

C#代码:

HtmlMeta meta = new HtmlMeta();
meta.Name = "Name1";
meta.Content = "this is a meta description's content";
MetaPlaceHolder.Controls.Add(meta);

【讨论】:

  • 如果您认为这符合downvote的条件,请添加评论
  • 首先它并不能解决问题,而且您的“最佳”方法包含错误。
猜你喜欢
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多