sebnilsson.com | Liquid Development Is What I Do
Seb Nilsson

ASP.NET MVC SEO-Framework

For any serious web-application you should always implement a solid Search engine optimization-strategy, but there is no standardized way to handle this in ASP.NET MVC, out of the box.

You could easily use the ViewBag-object to send dynamic values from Controller-Actions into Views, like this, for example:

public ActionResult Index()
{
    ViewBag.Title = "This is the page title";

    return View();
}

Then you'd have to make sure you correctly spell or copy-paste ViewBag.Title correctly into your View:

<head>
    <title>@ViewBag.Title</title>
    <!-- More head-values -->
</head>

One problem is that if you refactor the naming for ViewBag.Title into, for example ViewBag.Title, this will break the functionality, potentially site-wide, because you won't get any tooling-help from Visual Studio for the renaming.

This is why I created a framework for ASP.NET MVC SEO, to get structured and reusable functionality around the SEO-data for a web-application. The framework is available on Nuget, with the source-code on GitHub.

Using a SeoHelper-object, available inside Controllers and Views, you can set SEO-related data like:

  • Meta-Description
  • Meta-Keywords
  • Title, split on page-title and base-title (website-title)
  • Canonical Link
  • Meta No-index for robots

This can be done inside Controllers and Controller-actions:

[SeoBaseTitle("Website name")]
public class InfoController : SeoController
{
    [SeoTitle("Listing items")]
    [SeoMetaDescription("List of the company's product-items")]
    public ActionResult List()
    {
        var list = GetList();

        if (list.Any())
        {
            Seo.Title += $" (Total: {list.Count})";
            Seo.LinkCanonical = "~/pages/list.html";
        }
        else
        {
            Seo.MetaRobotsNoIndex = true;
        }

        return View(model);
    }
}

Or inside Views:

@{
    Layout = null;
    Seo.MetaRobotsNoIndex = true; // Always block Robots from indexing this View
}

These set values can easily be rendered as HTML-tags inside Views through provided HtmlHelper-extensions:

<head>
    @Html.SeoTitle()

    @Html.SeoLinkCanonical()
    @Html.SeoMetaDescription()
    @Html.SeoMetaKeywords()
    @Html.SeoMetaRobotsIndex()
</head>

See the README-file on GitHub for the latest detailed information about this ASP.NET MVC SEO-framework. Or try it out through Nuget by running Install-Package AspNetMvcSeo in your project. You can even follow the absolutely latest build on MyGet.

Comments