Asp.net Mvc: dynamic page title

In webforms, I've always used my master page to set page titles and meta descriptions based on the current url. I was thinking of doing the same for my Asp.net Mvc projects, but I'm not sure where to start. It would be nice to set the title / description based on the controller and / or action with some defaults, if I don't provide any information. The reason why I do this is because I like everything to be in one place because it makes it easier to spot bugs.

Edit:
After reading the answers and googling, I thought it would be great to get the information from the xml file. With Xml it looks 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'm new to Asp.net Mvc so don't know where to initialize it.

+2


source to share


3 answers


So, after a few days of trial work, I ended up creating a custom filter that reads from an XML file.

I added some code for copypastecode.com
http://www.copypastecode.com/9797/
http://www.copypastecode.com/9809/
http://www.copypastecode.com/9805/



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

The next thing I will try to do is do it without the filter so that it is activated on all controllers. Not sure where to connect the logic. So if anyone can nudge me in the right direction, let me know.

0


source


I suggest the following strategy:

Create a 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 title of the page, and you create base models to hold the default titles for the controller. This way, you can define a header in each action explicitly, or leave it to use the default header for that controller.



Then, in your main view, you simply write once:

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

      

and it's done.

+7


source


You can simply pull this data from the master page model and then let that model have reasonable defaults.

0


source







All Articles