views:

614

answers:

4

I am using the MVC to add a title to the masterpage with a content place holder. The default MVC masterpage template uses the following code:

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"/></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>

When I try to add defaulted text to the front of the content holder, it doesn't show the text in the final rendered page. I am trying to get the page to show a default title with appended contentplaceholder text.

Example:
(Default Text) (ContentPlaceHolder Text)
My Page - About Us

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My Page - <asp:ContentPlaceHolder ID="TitleContent" runat="server"/></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>

I am looking for a way to accomplish this without having to use code behind. Any ideas?

+1  A: 

If you are using MVC and are passing the title in some object from the controller to the page I would use inline code to display this.

We use the MVC contrib functions to get typed data directly from the view data in the master page thus:

<head>
<title>My Page - <%= ViewData.Get<Model.Page>().Title %></title>
</head>

As a point of note we have removed all code behind files from every view we have to make the views more legible, we find this much better than having code behind for each view.

Richard
That would take care of the problem, but I am trying to find a solution that could have the text "My Page" only on the master page. That way title changed it wouldn't need to be changed on each view. Thank you for responding though.
Aaron
+7  A: 

After looking further, Phil Haack actually posted an article which was a solution to my question. It can be found at Haacked.

In summary he said that everything that is rendered in the head is rendered as a control, and the fix for my question above is to put an asp literal control in the title to have it correctly generate the text.

<%@ Master ... %>
<html>
<head runat="server">
  <title>
    <asp:ContentPlaceHolder ID="titleContent" runat="server" /> 
    <asp:LiteralControl runat="server" Text=" - MySite" />
  </title>
</head>
...
Aaron
As mentioned by Alexander, this results in Unknown Server Tag exception.
Jonas Stawski
This works for me.
cottsak
Try using "Literal" instead of "LiteralControl"
rudib
+5  A: 

It seems we should use

<asp:Literal runat="server" Text=" - MySite" />

instead of

<asp:LiteralControl runat="server" Text=" - MySite" />

mentioned in the article, because otherwise we get "Unknown server tag" error.

Alexander Prokofyev
+2  A: 

Why?

<title>
    <asp:ContentPlaceHolder ID="titleContent" runat="server" />
    <%= "- My Site" %>
</title>

Works just as well. Without the hassle?

boymc