如何在ASP.NET MVC中传递页面的元标记?

时间:2020-03-06 14:49:40  来源:igfitidea点击:

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

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

我们如何处理这个?先感谢我们。

解决方案

这是我目前正在做的事情...

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

<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对博客帖子等有意义),并使其成为数据驱动。

把它放在你的viewdata中!做类似以下的事情...

BaseViewData.cs这是一个viewdata类,所有其他viewdata类都将从该class继承

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类。