Blankman
Blankman

Reputation: 267320

How to set the master page's html title from within a controller's action or view page?

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?

Upvotes: 1

Views: 827

Answers (3)

Brian
Brian

Reputation: 38035

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.

Upvotes: 1

Simon Fox
Simon Fox

Reputation: 10591

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>

Upvotes: 0

user151323
user151323

Reputation:

<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);
}

Upvotes: 2

Related Questions