How to pass page's meta tags in ASP.NET MVC?
Asked Answered
M

2

9

I'm playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great.

Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page).

How you're dealing with this? Thank you in advance.

Massasauga answered 27/9, 2008 at 17:29 Comment(0)
A
20

Here is how I am currently doing it...

In the masterpage, I have a content place holder with a default title, description and keywords:

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

And then in the page, you can override all this content:

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

This should give you an idea on how to set it up. Now you can put this information in your ViewData (ViewData["PageTitle"]) or include it in your model (ViewData.Model.MetaDescription - would make sense for blog posts, etc) and make it data driven.

Arroba answered 27/9, 2008 at 17:45 Comment(2)
This makes baby jebus cry... I know it goes against the MVC way but the ASP.net 4.0 Page.MetaDescription is flaming hohhhtttnesss Wish there was a simple way to do this on large sites in MVCChris
This solution is fine if you are developing a web forms application. However this is not the way to do it when building an MVC app. Please see Charlino's answer.Showoff
E
13

Put it in your viewdata! Do something like the following...

BaseViewData.cs - this is a viewdata class that all other viewdata classes will inherit from

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

Then your Site.Master (or whatever) class should be defined as follows:

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

Now in your Site.Master page simply have

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

And you're away laughing!

HTHs, Charles

Ps. You can then expand on this idea, e.g. put a getter to your User (IPrincipal) Class into a LoggedInBaseViewData class.

Erosive answered 29/9, 2008 at 4:19 Comment(1)
If I was to rewrite this for today, I would do this using the ViewBag.Erosive

© 2022 - 2024 — McMap. All rights reserved.