Adding Metatags on .cshtml Pages in MVC

This quick article is a response to a question I received today on Facebook. Please use the following procedure 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 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 a page we can define.
 
Step 3
 
Now, open your .cshtml page where you wish to add metatags and add the following section reference:
 
 
 
Step 4
 
Now, open the page in a browser and you will see your metatags in action.
 
 
 
Advanced
 
We can also make these metatags dynamic, in other words, we can control them from controllers.
 
Controller
  1. public ActionResult Index()  
  2. {  
  3.     ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";  
  4.     ViewBag.MetaKeywords = "abc";  
  5.     ViewBag.MetaDescription = "abc";  
  6.     return View();  
  7. }
Section on .cshtml page
  1. @section metatags {  
  2.     <meta name='keywords' content='@ViewBag.MetaKeywords'/>  
  3.     <meta name='description' content='@ViewBag.MetaDescription'/>  
  4. } 
Hope this helps.


Similar Articles