Adding MVC Meta Tags to razor pages

In every View we can assign different meta tags (title, description, keywords, etc) however it is not very clear to every one how this is achieved. In reality this is quite easy.

So here it goes:

In your “_Layout.cshtml” paste the following in your head section:

@if(ViewBag.Description!=null)
{
<meta name=”description” content=”@ViewBag.Description” />
}
@if(ViewBag.Keywords!=null)
{
<meta name=”keywords” content=”@ViewBag.Keywords” />
}

 

Now, in your other pages which will inherit from the layout, at the very top where you usually have Viewbag.Title defined, add the following Viewbags:

@{

ViewBag.Title = “Home Page”;
ViewBag.Description = “Welcome to Rochcass Blog”;
ViewBag.Keywords = “C# posts, errors and solutions, problem solving, css3, html5, ASP.NET, Linq, MVC, Nhibernate”;
}

 

You can do the same for other meta tags such as author, etc.

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s