views:

803

answers:

4

Hello, in webforms I would always use my masterpage to set page titles and meta description based on the current url. I was thinking of doing the same for my Asp.net Mvc projects but I ain't sure where to start. It would be nice to be able to set the title/description based on the controller and/or action with some default values incase I don't specify any info. The reason why I do this is because I like everything to be in one place because that makes it easy to spot mistakes.

Edit:
After reading the answers and googling some I was thinking it might be cool to get the info from an xml file. With Xml looking something like this:

<website title="default title for webpage">
    <controller name="HomeController" title="Default title for home controller"> 
       <action name="Index" title="title for index action" />
    </controller>
</website>

I am new to Asp.net Mvc so I am not sure where to initialize this.

A: 

You could simply pull that data from the master page's Model, then let that Model have some reasonable defaults.

Mark Seemann
+4  A: 

I suggest the following strategy:

Create an hierarchy of models:

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

abstract class HomeBaseModel : MasterModel
{
    PageTitle = "Home";
}

abstract class UsersBaseModel : MasterModel
{
    PageTitle = "Users";
}

/************************************/

class HomeNewsModel : HomeBaseModel
{
    PageTitle = "News";
}

class UsersProfileModel : UsersBaseModel
{
    PageTitle = "Profile";
}

You define a master model to hold the page title and you create base models to hold default titles for a controller. This way, you can define the title in each action explicitly or leave it out so that the default title for this controller will be used.

Then in your master view you just write once:

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

and it's done.

Developer Art
How does this model get exposed to the master page? I am a noob at this.
Josh Stodola
A: 

Similar question with answers here

bh213
A: 

So after a few days of trying stuff I ended up with making a custom filter that reads from a XML file.

I added the code to copypastecode.com
http://www.copypastecode.com/9797/
http://www.copypastecode.com/9809/
http://www.copypastecode.com/9805/

I am very novice at Asp.net Mvc and "real" C# coding so if you see strange stuff please forgive me. If somebody wants to optimize it or has a better solution feel free to post it as an answer.

Next thing I am gonna try is to make it without a filter so it's activated on all controllers. Not sure where to hook up the logic though. So if anybody can push me into the right direction let me know.

Pickels