简体   繁体   中英

Curious problem with the ContentPlaceHolder in the HTML Title tag of the masterpage (MVC2)

Ok, I'm sure it must be a silly mistake on my part, but I can't find where the problem is, and it's driving me nuts.

I have a master page, with this:

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

It's just the default HTML inserted by VS when I created the masterpage, I just added " - Company" at the end, so that I don't have to repeat that text in every single view.

On the views, I have, for example, this:

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Some title for the view
</asp:Content>

As you can imagine, the final result is not what I expected. Instead of

<title>Some title for the View - Company</title>

I'm getting:

<title>Some title for the View</title>

Why?

Seems to be a quirk about how Classic ASP.Net (aka WebForms) works. Phil Haacked on Title Tags and Master Pages is a great read.

Although he goes into depth about the reasons it works the way it does, it seems he isn't referring to MVC specifically. The first comment by Erik Porter has the crazy easy solution:

Change

<head runat="server">

to

<head>

Tada, fixed.

Try this inside your title tag:

<asp:ContentPlaceHolder ID="TitleContent" runat="server" /><%= " - Company" %>

I ran into this a while back and putting the literal inside a code block cleared it up. I'm not really sure why, though, if someone has an explanation.

You have closed the title tag twice. Also, try not having the ContentPlaceHolder be self closing.

In MVC, I don't recall ever using the ContentPlaceHolder. I strongly type my master page and populate the master page that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM