Author image

Weston Walker

I'm a full stack developer 🤓 who's a teacher at heart. I create awesome web applications and want to help you do the same. I release new content a couple times a week.


Subscribe to the newsletter to get updates on new posts, articles, videos, projects.....

What's My Name Again? - ASP.NET DRY Page Titles

Don't repeat yourself copying a string to repeat your page titles in ASP.NET. Learn how to set a page title once, for every page.

Published May 30, 2020

A common pattern for page titles is something along the lines of "Site Name - Page Name" or "Page Name - Site Name". The "Page Name" part of this string can be set in the individual page views. But what about the "Site Name" part that you will want in every view?

Setting up a partial page title in your _Layout.cshtml file can prevent the duplication of code. In your _Layout.cshtml file, add a title tag in your head tag like so:
<title>@ViewData["Title"] - Site Name</title>
Now in your individual page views you can set the `ViewData["Title"]`. If we were to set the title in our Index.cshtml file to Home Page...
    ViewData["Title"] = "Page Name";
The title in the browser would now be "Home Page - Weston Walker".