1

I have a controller's action and view page that uses a master page.

The master page has the html title section like:

<title>this is the page's title</html>

How can I access this section from within my controller's action (preferably) or my action's view page?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

2
<title><%= Model.PageTitle %></html>

public class MasterModel
{
    public string PageTitle { set; get; }
}

public class MyViewModel : MasterModel
{
    /* ... */
}

You can set the base class PageTitle property in a controller action all you want.

public ActionResult SomeAction ()
{
    MyViewModel model = new MyViewModel ();
    model.PageTitle = "this is the page's title";

    return View (model);
}
  • How do I get the master page to use the MasterModel though? You are refering Model in the master page? – Blankman Mar 10 '10 at 21:07
  • Ok I just referenced the base model in the master, thanks ALLOT! – Blankman Mar 10 '10 at 21:08
  • Yep, the master page would be strongly-typed to the base class (MasterModel), while the views would use the derived model classes. –  Mar 10 '10 at 21:11
1

The way I typically handle setting the title of html pages is through the pages Title property.

In my view I have this...

<%@ Page Language="C#" Title="Hello World" ... %>

And in my master page I have this...

<title><%=Page.Title%></title>

If you want to have the controller set the page title you will probably have to send the title in through the view model.

Brian
  • 37,399
  • 24
  • 94
  • 109
0

Pop the title you want into ViewData from the Action method and then just render it to the page...

In action method

ViewData["PageTitle"] = "Page title for current action";

On master page

<!-- MVC 1.0 -->
<title><%=Html.Encode(ViewData["PageTitle"]) %></title>

<!-- MVC 2.0 -->
<title><%: ViewData["PageTitle"] %></title>
Simon Fox
  • 10,409
  • 7
  • 60
  • 81