views:

35

answers:

3

Is there a way to programmatically access and modify the <head> section of the page in ASP.NET MVC? I need to update the page's <meta> tags depending on which data the user is viewing on any given page.

+1  A: 

Try:

<meta name="description" content="<%: Model.Meta %>" />
Jakub Konecki
Just to note, using the second approach you will probably need to create a BaseViewModel to use this more effectively.
Ahmad
HttpContext.Current.Response.Headers returns actually a collection of the response http headers. It has nothing to do with the <head> html element.
Branislav Abadjimarinov
+1  A: 

You could use a content placeholder in the master page which you override in each view:

<head>
    <title>
        <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <asp:ContentPlaceHolder ID="Metas" runat="server" />
...

and in the view:

<asp:Content ID="IndexMetas" ContentPlaceHolderID="Metas" runat="server">
    <meta name="keywords" content="some keywords specific to the view" />
</asp:Content>
Darin Dimitrov
+1  A: 

In ASP.NET 4.0 there are several new properties of the Page which you can use to set meta-tags directly like this:

Page.MetaKeywords = "asp.net,c#"; 
Page.MetaDescription = "This is my stackoverflow post";

You can read more about them here http://weblogs.asp.net/dotnetstories/archive/2010/03/23/asp-net-4-0-meta-tags-and-search-engine-optimisation.aspx

Branislav Abadjimarinov