最近几天我在玩 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,查尔斯
附言。然后您可以扩展这个想法,例如将您的 User (IPrincipal) 类的 getter 放入 LoggedInBaseViewData 类。