How To Add Metatags on .cshtml Pages in MVC

I am writing this blog post because a friend was working on this project, and we needed to ensure we had it all set up for SEO. We needed to add the essential SEO page title, keywords, and meta description. To simplify things, we used a few view bags in the action method to pass the data to the views. Simple enough, right? Well, I decided to put a quick, simple application together to show how that was implemented.

  • First of all, let’s create a new .Net Core MVC application and called it MetaTagsMvc
  • Next, select the framework which you want to use for this app. I am using .Net 6.0 in the scenario.
  • Once the project is created, go inside the views folder and find the “Shared” folder which contains the layout page that is named “Layout.cshtml”.
  • Open the layout.cshtml file and paste this line of code in there inside the header section
    @RenderSection("metatags", required:false)

The @RenderSection(“metatags,” required: false) code is a Razor syntax in an ASP.NET MVC view that we’ll use to render the content of a section named “metatags” if it exists in the view. Let’s set the required parameter to false since that section is not required, and it can be omitted if it’s not defined in the view.

  • Now, we can use any view to add the metatag, in this example, I’ll use the index.cshtml found in the home folder under views.
  • Add this section at the top of that page as shown below
@section metatags{
    <meta name="keywords" content="@ViewBag.Keywords" />
    <meta name="description" content="@ViewBag.Description" />
}
  • Finally, we’re ready to pass in the keywords and description to the view using ViewBags. Copy those two lines of code in the index.cshtml file as shown below.
ViewBag.Keywords = "Keyword1, Keyword2, Keyword3, Keyword4, Keyword5";
ViewBag.Description = "Testing how to add metatags to an MVC applicaiton";

Now, we’re all set. Simply run the application now by pressing F5. Find this project repo: MetaTagMvc

Leave Comment

Your email address will not be published. Required fields are marked *