0

What I'd like to do seems pretty simple. I'd like to specify the page title in my @Page directive on a view, like so:

<%@ Page Title="About This Site" ... %>

Then, I'd like to get that page title into the ViewData, so that it could be used in the master page, like:

<head>
    <title>The Awesome Site | <%=ViewData["Title"]%></title>

And also in the View itself like:

<h1><%=ViewData["Title"]%></h1>

I am already inheriting a custom controller for all of the page controller methods. So I'm hoping that there's something I can do in the controller to transfer the Page.Title property into the ViewData (or maybe I'll use the ViewBag). I just can't seem to find any route to reference the Page from within the Controller.

Is this possible? Is there a different approach I might want to consider.

OneCleverMonkey
  • 422
  • 4
  • 15

2 Answers2

1

See "generic errors" post on this for a clean way to do this.

Passing data to Master Page in ASP.NET MVC

you should not be referencing anything from a "page" from a controller. The two are completely separate by design. You need to package your data and then send it to the view. Another way (more like what you are requesting) is that you use @{

ViewBag.Title ="my view title"; } Then the master page uses that value wherever you want it.

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • use razor syntax then @{ViewBag.Title="whatever";} at the top of your view - much smaller, easier for them to change – Adam Tuliper May 12 '11 at 15:04
0

I think you might be looking for Html.Title().

You can write this to any part of the page:

<title><%: Html.Title() %></title>

This will pickup the title from your view and insert it into your master page as required.

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
  • 1
    No luck with this one. I got "'System.Web.Mvc.HtmlHelper' does not contain a definition for 'Title' and no extension method 'Title' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)" – OneCleverMonkey May 12 '11 at 14:13