【发布时间】:2008-09-27 17:29:17
【问题描述】:
最近几天我一直在使用 ASP.NET MVC,并且能够构建一个小型站点。一切都很好。
现在,我需要通过 ViewData 传递页面的 META 标签(标题、描述、关键字等)。 (我使用的是母版页)。
你是如何处理这个问题的?提前谢谢你。
【问题讨论】:
最近几天我一直在使用 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 - 对博客文章等有意义)并使其成为数据驱动的。
【讨论】:
把它放在你的视图数据中!执行以下操作...
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。