2010-01-15

ASP.NET MVC - Easy way to manage page title

Hi,

As a developer it’s always a pain to manage titles for each page of a web application :)

1 – Create an ActionFilterAttribute

/// <summary>
/// Specifies the title and keywords for the page
/// </summary>
public class HeaderAttribute : ActionFilterAttribute
{
private string _title;

public HeaderAttribute(string title)
{
_title = title;
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);

if (filterContext != null && filterContext.Controller != null)
{
filterContext.Controller.ViewData["_Title"] = _title;
}
}
}

2 – Add the title in the Master Page


Here’s the code to add in the master page. Don’t forget to put it in all your Master Pages…


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><%= ViewData["_Title"]%></title>
<meta name="title" content="<%= ViewData["_Title"] %>" />
</head>

3 – Put the attribute to your actions


You can now use the attribute over a controller (each action will have the title) or an action.


[Header("My Web Site - Default Page")]
public class HomeController : BaseController
{
[Header("My Web Site - Home")]
public ActionResult Index()
{
return View();
}

// The title will be "My Web Site - Default Page"
public ActionResult Buy()
{
return View();
}
}

That’s it! You can also add other specific action <meta> tags like keywords and description.


3 comments:

  1. Do you have other examples that use an ActionFilterAttribute?

    ReplyDelete
  2. Yes, i'm managing security with ActionFileAttribute. I will make a new blog post soon to show it. Here's the code of the attribute :

    ///
    /// Specifies that the method or class is a secured action that requires authorization before being executed.
    ///
    public class SecuredActionAttribute : ActionFilterAttribute
    {
    public string Key { get; set; }

    public SecuredActionAttribute(string key)
    {
    this.Key = key;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
    if (!(filterContext.Controller.GetType() == typeof(HomeController) && (filterContext.RouteData.Values["action"] as string) == "Unauthorized"))
    {
    if (!Container.Resolve().IsAuthorized(this.Key))
    {

    filterContext.Result = ((GSCController)filterContext.Controller).RedirectToUnauthorized();
    }

    base.OnActionExecuting(filterContext);
    }

    }

    ReplyDelete