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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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.
1 2 3 4 5 |
@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.
Keep Cool Coding….
Leave A Comment