Dynamically Adding meta tags in asp.net mvc

In this blog post, I am going to explain how we can create a meta tag dynamically using Asp .Net MVC. We are aware that Meta tag plays very important roles in Search engine optimization. It is necessary to add meta tag for best ranking on search engines. Let we discuss with simple example.

Controller :

From the below code, BindMetaTag method which will return a string with meta tags. This method will create a meta tag string and it will return to the calling method. Here I am using view bag to store the dynamically created meta tag string for binding in the view.

public ActionResult Index()
{
ViewBag.LoadMetaTag = BindMetaTag();
return View();
}

public string BindMetaTag()
{
System.Text.StringBuilder strDynamicMetaTag = new System.Text.StringBuilder();
strDynamicMetaTag.AppendFormat(@"<meta content='{0}' name='Keywords'/>", "Dotnet-helpers");
strDynamicMetaTag.AppendFormat(@"<meta content='{0}' name='Descption'/>", "creating meta tags dynamically in"+ " asp.net mvc by dotnet-helpers.com");
return strDynamicMetaTag.ToString();
}

View :

Here in the below code, @Html.Raw method is used to embed meta tag in _layout.cshtml page. This HTML.Raw method will embed output to head tag section without encoding html.

@Html.Raw(ViewBag.LoadMetaTag)

<h2>Dynamically creating meta tags in asp.net mvc</h2>

OutPut :

Now once you run your application and click on view source you will find meta tag for home page as show below.

dotnet-helpers-adding meta tag using mvc -thiyagu

 

Keep Cool Coding….

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.