【问题标题】:How to pass page's meta tags in ASP.NET MVC?如何在 ASP.NET MVC 中传递页面的元标记?
【发布时间】:2008-09-27 17:29:17
【问题描述】:

最近几天我一直在使用 ASP.NET MVC,并且能够构建一个小型站点。一切都很好。

现在,我需要通过 ViewData 传递页面的 META 标签(标题、描述、关键字等)。 (我使用的是母版页)。

你是如何处理这个问题的?提前谢谢你。

【问题讨论】:

    标签: asp.net-mvc master-pages


    【解决方案1】:

    这是我目前的做法......

    在母版页中,我有一个带有默认标题、描述和关键字的内容占位符:

    <head>
    <asp:ContentPlaceHolder ID="cphHead" runat="server">
        <title>Default Title</title>
        <meta name="description" content="Default Description" />
        <meta name="keywords" content="Default Keywords" />
    </asp:ContentPlaceHolder>
    </head>
    

    然后在页面中,你可以覆盖所有这些内容:

    <asp:Content ID="headContent" ContentPlaceHolderID="cphHead" runat="server">
        <title>Page Specific Title</title>
        <meta name="description" content="Page Specific Description" />
        <meta name="keywords" content="Page Specific Keywords" />
    </asp:Content>
    

    这应该让您了解如何设置它。现在您可以将此信息放入您的 ViewData (ViewData["PageTitle"]) 或将其包含在您的模型中(ViewData.Model.MetaDescription - 对博客文章等有意义)并使其成为数据驱动的。

    【讨论】:

    • 这让婴儿 jebus 哭了...我知道这与 MVC 方式背道而驰,但 ASP.net 4.0 Page.MetaDescription 正在燃烧 hohhhtttnesss 希望有一种简单的方法可以在 MVC 中的大型网站上执行此操作
    • 如果您正在开发 Web 表单应用程序,此解决方案很好。但是,这不是构建 MVC 应用程序时的方法。请参阅 Charlino 的回答。
    【解决方案2】:

    把它放在你的视图数据中!执行以下操作...

    BaseViewData.cs - 这是一个所有其他 viewdata 类都将继承自的 viewdata 类

    public class BaseViewData
    {
        public string Title { get; set; }
        public string MetaKeywords { get; set; }
        public string MetaDescription { get; set; }
    }
    

    那么您的 Site.Master(或其他)类应定义如下:

    public partial class Site : System.Web.Mvc.ViewMasterPage<BaseViewData>
    {
    }
    

    现在在您的 Site.Master 页面中只需拥有

    <title><%=ViewData.Model.Title %></title>
    <meta name="keywords" content="<%=ViewData.Model.MetaKeywords %>" />
    <meta name="description" content="<%=ViewData.Model.MetaDescription %>" />
    

    然后你就笑了!

    HTH, 查尔斯

    附言。然后你可以扩展这个想法,例如将您的用户(IPrincipal)类的吸气剂放入 LoggedInBaseViewData 类。

    【讨论】:

    • 如果我今天要重写这个,我会使用ViewBag
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多