April 8, 2013 09:08 by
Scott
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 you .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
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.