Adding metatags on .cshtml pages in MVC

This quick post is a response to a question I received today on Facebook. Please follow the steps to add metatags on .cshtml pages:-

Step 1

When we create a MVC4 Application using an Internet Template we get a ‘Shared’ folder inside the ‘Views’ folder on the root and in the ‘Shared’ folder you will find a layout page by named ‘_Layout.cshtml’. Open that file.

Step 2

In the ‘_Layout.cshtml’ page add a new section call inside the <head> tag, as given below:

In the above image you can see that a section call is not required; in other words whenever we need metatags on page we can define.

Step 3

Now, open .cshtml page where you wish to add metatags and add the following section reference:

Step 4

Now, open the page in a browser you will see your metatags in action.


We can also make these metatags dynamic, in other word we can control them from controllers.


public ActionResult Index()
    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

    ViewBag.MetaKeywords = "abc";
    ViewBag.MetaDescription = "abc";

    return View();

Section on .cshtml page:-

@section metatags {
    <meta name='keywords' content='@ViewBag.MetaKeywords'/>
    <meta name='description' content='@ViewBag.MetaDescription'/>

Hope this helps.


Post a Comment

Popular posts from this blog

Lambda two tables and three tables inner join code samples