2

Has anyone here structured your views, controller and actions in such a way that the page titles are set from the database. How do you identify one view from another ? In which phase of the lifecycle do you retrieve the page title and set it for the view/action method a lot of posts are scattered for asp.net, php but then a efficient way for mvc I am yet to find

Deeptechtons
  • 10,945
  • 27
  • 96
  • 178
  • well, if you set on controller the `ViewBag.Title = "String comes from Database"` que do not set on View, it will work fine. – Felipe Oriani Dec 21 '12 at 10:23
  • @FelipeOriani that would be lame wouldn't it? doing this in every controller action method god no i would go in maintenance nightmare then – Deeptechtons Dec 21 '12 at 10:24

2 Answers2

4

You could use action filters:

public class ControllerAndActionNameAttribute : ActionFilterAttribute
{        
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.ControllerName = filterContext.RequestContext.RouteData.Values["controller"].ToString();
        filterContext.Controller.ViewBag.ActionName = filterContext.RequestContext.RouteData.Values["action"].ToString();
        base.OnActionExecuting(filterContext);
    } 
}

But instead of putting the action- or controllername into the viewbag, you could load stuff from your database based on action and/or controller.

b_meyer
  • 594
  • 2
  • 7
  • awesome i was just going through a article to do that.http://stackoverflow.com/questions/9462761/executing-code-before-a-controllers-method-is-invoked – Deeptechtons Dec 21 '12 at 10:41
1

What if you have service or helper method that retrieves all the titles from the database and stores them to some sort of cache or static variable think Dictionary. Depending on how you plan to update with the site running determines when or how.

Then expose a static helper method that the views can call to retrieve their title.

You could probably even incorporate a T4 template to set a property for each view to call the method with the correct retrieval key

Michael Christensen
  • 1,768
  • 1
  • 13
  • 11
  • What's unique about each view that i can use to retrieve the page titles? Is there a method that executes before a controller action executes so that i can hook there get the title for Controller & ActionMethod finally setting it in the viewbag – Deeptechtons Dec 21 '12 at 10:39