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.