Dynamically add meta tags in Asp .Net MVC

In this asp .net mvc tutorial we will learn about How to Dynamically add page title and meta tags from database. Meta Title and Meta tags plays a great role in SEO of any website. This information is used by search engines to influence your webpage presentation.

Our Mission:

  1. Create database to store information of title, Meta Keywords and Meta Descrition for each page.
  2. Create functionality to get information from database and assign title, Meta Keywords and Meta Descrition to each page when it is browsed.

Step 1: Create a new asp .net mvc project.

After creating project you will notice 3 views are created by default. (I have created Internet Application)
  1. Index
  2. About
  3. Contact
Note: If you have created blank project then add a controller named Home and add above mentioned actions with views to HomeController.

Step 2: Run the project and check existing tags.

Run the project and navigate to each page and view Page Source to check what tags are present in head section of each page.

  1. Home Page:
  2. Dynamically add meta tags in Asp .Net MVC

  3. About Page:
  4. Dynamically add meta tags in Asp .Net MVC

  5. Contact Page:
  6. Dynamically add meta tags in Asp .Net MVC
From the above images we can see that only title tag is present. There are no Meta Keywords and Meta Description tags available.

Step 3: Create a Database table:

In this step we will create database table to store information. Dynamically add meta tags in Asp .Net MVC

Step 4: Insert data into database:

Add sample data into database table. Dynamically add meta tags in Asp .Net MVC Note: Here PageUrl Column contains information in following format: Contoller/Action. You can modify values of this column according to your routing structure.

Script to generate database table with values:

    CREATE TABLE [dbo].[PageMetaDetail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[PageUrl] [nvarchar](50) NULL,
	[Title] [nvarchar](50) NULL,
	[MetaKeywords] [nvarchar](100) NULL,
	[MetaDescription] [nvarchar](100) NULL,
     CONSTRAINT [PK_PageMetaDetail] PRIMARY KEY CLUSTERED 
    (
	    [ID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO
    SET IDENTITY_INSERT [dbo].[PageMetaDetail] ON 

    GO
    INSERT [dbo].[PageMetaDetail] ([ID], [PageUrl], [Title], [MetaKeywords], [MetaDescription]) VALUES (1, N'Home/Index', N'MVC Tutorials', N'mvc,tutorials,examples', N'High quality mvc tutorials and examples')
    GO
    INSERT [dbo].[PageMetaDetail] ([ID], [PageUrl], [Title], [MetaKeywords], [MetaDescription]) VALUES (2, N'Home/About', N'About Our Company', N'about,about2,about3', N'All you need to know about our company')
    GO
    INSERT [dbo].[PageMetaDetail] ([ID], [PageUrl], [Title], [MetaKeywords], [MetaDescription]) VALUES (3, N'Home/Contact', N'Need Help? Contact', N'contact,contact2,contact3', N'Any mvc realated question? contact us.')
    GO
    SET IDENTITY_INSERT [dbo].[PageMetaDetail] OFF
    GO
    

Step 5: Add a new class

To add new class inside models folder. I have named it PageMetaDetails Dynamically add meta tags in Asp .Net MVC Dynamically add meta tags in Asp .Net MVC

Step 6: Add method to class

In this step we will create a new method inside our class to fetch data from database and retrun title, Meta Keywords, Metadescription based on Page selected.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MvcApplication_DynamicMeta.Models
{
    public class PageMetaDetail
    {
        public static string UpdateMetaDetails(string pageUrl)
        {
            //--- StringBuilder object to store MetaTags information.
            StringBuilder sbMetaTags = new StringBuilder();

            //--Step1 Get data from database.
            using (myEntities db = new myEntities())
            {
                var obj = db.PageMetaDetails.FirstOrDefault(a => a.PageUrl == pageUrl);

                //---- Step2 In this step we will add  tag to our StringBuilder Object.
                sbMetaTags.Append("<title>" + obj.Title + "");
                sbMetaTags.Append(Environment.NewLine);

                //---- Step3 In this step we will add "Meta Description" to our StringBuilder Object.
                sbMetaTags.Append("");
                sbMetaTags.Append(Environment.NewLine);
                //---- Step4 In this step we will add "Meta Keywords" to our StringBuilder Object.
                sbMetaTags.Append("");
            }
            return sbMetaTags.ToString();
        }
    }
}
    
Note: In above method I have used entity framework to fetch data from database. If you are not familiar with Entity Framework you can check this tutorial:
Add insert update delete using entity framework database first in asp net-a step by step example

Step 7: Call method from head section of page

In this step we will call UpdateMetaDetails method from head section of page to Update title and meta information from database. Since all our views are using layout to render consistent look. We need to modify _Layout.cshtml in order to update head section. Go to Share folder and Locate _Layout.cshtml

Dynamically add meta tags in Asp .Net MVC

Remove already used title and and add following code inside head section of _Layout.cshtml:

   @{
        string currentUrl = Url.RequestContext.RouteData.Values["controller"] + "/" + Url.RequestContext.RouteData.Values["action"];
        @(Html.Raw(MvcApplication_DynamicMeta.Models.PageMetaDetail.UpdateMetaDetails(currentUrl)));
    }
   

Final Output

  1. Home Page:
  2. Dynamically add meta tags in Asp .Net MVC

  3. About Page:
  4. Dynamically add meta tags in Asp .Net MVC

  5. Contact Page:
  6. Dynamically add meta tags in Asp .Net MVC
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice