ASP.NET MVC - View with master page, how to set title?

bh213 picture bh213 · Nov 28, 2008 · Viewed 26k times · Source

What is prefered way of setting html title (in head) for view when using master pages?

One way is by using Page.Title in .aspx file, but that requires in master page which can mess with HTML code. So, lets assume no server side controls, only pure html. Any better ideas?

UPDATE: I would like to set title in view NOT in the controller or model.

Answer

Andrew Csontos picture Andrew Csontos · Mar 17, 2009

In our master pages, we created both an "init" ContentPlaceHolder, and a "title" ContentPlaceHolder. If someone wants to programatically set Page.Title, they can set it in CSharp in the init placeholder, or they can override the "title" placeholder using tags.

Master Page

<asp:ContentPlaceHolder id="init" runat="server"></asp:ContentPlaceHolder>
<head runat="server">    
    <asp:ContentPlaceHolder ID="title" runat="server">
        <title><%=this.Page.Title%></title>
    </asp:ContentPlaceHolder>
</head>

View Page Could either override the entire "title" content placeholder:

<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
       <title>Home Page</title>
</asp:Content>

or programatically set the page title.

<asp:Content ID="Content1" ContentPlaceHolderID="init" runat="server">
    <%this.Title = "Home Page";%>
</asp:Content>

Make sure you remove the Title="" from the Page directive at the top, or you won't be able to programatically change Page.Title.