How to add dynamic meta tags to your asp.net mvc views

Setting Up

We'll start by creating a new ASP.NET MVC 5 project and we'll make sure we have individual accounts selected. We're doing this so that we get entity framework and our dbcontext out-of-the-box. 

94f32fe3-cd15-473a-8872-884f09f545f1newProjectIndividualAccountsSelected.PNG

In your new project, let's create two models. We'll make a Page model and a MetaViewModel. The Page model will contain all of the properties that we'll be using in our database, the MetaViewModel will be used to shape the data for rendering our partial view. This will make perfect sense when you see it in context.

Adding Models

So let's create our Page.cs file in our model's folder and then we'll add the following code:

 
    
public class Page
{
    public int Id { get; set; }
    public string Author { get; set; }
    public string Keywords { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

and we'll go ahead an add our MetaViewModel as well in the same manor, here's the code:

    
public class MetaViewModel
{
    public string Author { get; set; }
    public string Keywords { get; set; }
    public string Description { get; set; }
}

Let's continue by adding our Page class to our dbcontext by creating a new property for it in our IdentityModels file (in your model folder). We're just going to add one line, like so:

    
public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext() 
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet Pages { get; set; } // this is the line we're adding
}

Build your project but don't actually run it yet.

Controller Logic

Now that we've built our project the compiler knows about our new models for sure. Let's add a controller by right-clicking on the controller folder and selecting add > controller.

We'll choose to create an "MVC 5 Controller with views using Entity Framework", you'll see a form appear add the following constraints: 

071552d9-9f98-4712-a71a-45d9c1f73879createPagesController.PNG

We'll put our MetaViewModel to use in our new PagesController, add the following Action Result to your controller.

    
public ActionResult ListMeta(int? id = 1)
{
    var post = db.Pages.Find(id);

    MetaViewModel meta = new MetaViewModel();
    meta.Author = post.Author;
    meta.Keywords = post.Keywords;
    meta.Description = post.Description;

    return PartialView("~/Views/Pages/_ListMeta.cshtml", meta);
}

We'll need a Partial View

Notice that we're returning a partial view in this method, obviously that doesn't exist yet, so we'll need to make that now. Right click on your "ListMeta" method and select Add View. A dialog window will appear, make sure you fill it out just as I've done below.

76ed1ee5-5eba-4af3-8e87-8812e8afdbf4metaform_partial.png

Once your new partial view is created lets replace the code with the following:

    
@MetatagsExample.Models.MetaViewModel

< meta name="description" content="@Html.DisplayFor(modelItem => Model.Description)">
< meta name="keywords" content="@Html.DisplayFor(modelItem => Model.Description)">
< meta name="author" content="@Html.DisplayFor(modelItem => Model.Author)">

Lets open up our Details page for this controller by going to Views > Pages > Details.cshtml, we'll add the following lines to the top of our class (just below our @model code): 

 
    
@section metatags {
    @Html.Action("ListMeta", "Pages", new { id = Model.Id })
}

Now, lets open our _Layout.cshtml, which acts as a template for all of our future Pages and we'll add the following line inside our <head> tags:

    
@RenderSection("metatags", false)

Alright, we're ready to create our database!

Open your package manager console window by selecting view > other windows > package manager console. Once your console has opened we're going to run the following three commands individually.

  • enable-migrations
  • add-migration initial
  • update-database

If everything was successful, you now have a local database which will serve nicely for our example.

Build and Run

Finally, lets build and run our project. Once your project compiles and the browser opens. Navigate to the following URL:

localhost:{port}/pages/create

You'll see a create form, fill it out and click create. You've just created a "Page" that contains your specified meta data. After your record posts, you'll see a new screen with the results. Click the "details" link and you'll be taken to the details page.

Right-click and choose "View Source" and you should see your specified source as I've shown below

c59d96ea-e78a-4eef-8e25-f16ebd5228f2pagesource.png

That's it... If you have any problems just leave a comment and I'll try to clarify for you.