Maricel
Maricel

Reputation: 135

How can I add meta description and title to my MVC3 pages?

Can someone tell me if there is a recommended way to add Meta information to MVC3 pages. The kind of information that I would like to add is title, description, keywords.

Thanks,

Gemma

Upvotes: 3

Views: 2499

Answers (4)

jglouie
jglouie

Reputation: 12880

I'd use ViewBag for the title and RenderSection for the rest of the head content. This goes in the Master Layout file (_Layout.cshtml):

<head>
    <title>@ViewBag.Title</title>
    @RenderSection("head", false);
</head>

In your individual views, you will add:

@{
    ViewBag.Title = "My Page Title";
}

@section head {
    <meta name="description" content="best site ever">
}

EDIT:

Note that the @section head {...} block is optional. You will not get a compilation error if you omit this block. On views where you want metadata you'd supply it.

Upvotes: 6

Alexander Beletsky
Alexander Beletsky

Reputation: 19821

You have to put metatags inside the HEAD tag of HTML. For MVC application it depends there you have HEAD. It could be either page (*.cshmtl) of layout (Layout.cshtml). It is quite better to place into layout, since meta info is shared throught the rest of pages.

// *.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
   <meta ... />
</html>
</head>

Upvotes: 0

Ken D
Ken D

Reputation: 5968

Usually, in master page, we put a ContentPlaceHolder control, call it TitleContent like this:

<head>
    <title>
        <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
    </title>
</head>

And in children pages:

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Some Title
</asp:Content>

The same thing can be done for Meta Tags, or you could make a full ContentPlaceHolder for HeadContent and fill it with (title/meta...) in each page individually.

Upvotes: 0

user156888
user156888

Reputation:

I'd add it as a seperate view - that way you can call:

@{Html.RenderAction("Head", "Header");}

from within your various layouts and have the same correct header data rendered.

hth

Upvotes: 0

Related Questions