我需要在每個頁面上放置獨特的描述和關鍵字元標籤。試過這個。但它沒有點擊。Razor Engine - SEO Meta標籤
@{
ViewBag.Title = "Title";
ViewBag.Description = "Test";
ViewBag.Keywords = "Test1, Test2, Test3";
}
如何將元標記置於MVC 3 Razor引擎中?
我需要在每個頁面上放置獨特的描述和關鍵字元標籤。試過這個。但它沒有點擊。Razor Engine - SEO Meta標籤
@{
ViewBag.Title = "Title";
ViewBag.Description = "Test";
ViewBag.Keywords = "Test1, Test2, Test3";
}
如何將元標記置於MVC 3 Razor引擎中?
在佈局可以定義一個部分:
<head>
...
@RenderSection("metas")
</head>
,並考慮:
@section metas
{
<meta name="description" content="Test" />
<meta name="title" content="Title" />
<meta name="keywords" content="Test1, Test2, Test3" />
...
}
或佈局:
<head>
<meta name="description" content="@ViewBag.Description" />
<meta name="title" content="@ViewBag.Title" />
<meta name="keywords" content="@ViewBag.Keywords" />
...
</head>
並在視圖中:
@{
ViewBag.Title = "Title";
ViewBag.Description = "Test";
ViewBag.Keywords = "Test1, Test2, Test3";
}
您需要發出在佈局網頁<meta>
標籤使用的值。
您可以通過編寫@ViewBag.Description
來獲取標籤中的值。
你可以做你沒有,但你必須給他們在你的_Layout.cshtml鏈接。在<head>
部分添加到您的_Layout.cshtml:
@if(ViewBag.Description!=null)
{
<meta name="description" content="@ViewBag.Description" />
}
@if(ViewBag.Keywords!=null)
{
<meta name="keywords" content="@ViewBag.Keywords" />
}
使用'@if(ViewBag.Description!= null)'的原因是什麼? – 2016-12-24 11:16:25
因此,如果不需要,它不會添加標籤。 – 2017-01-24 13:44:48
我想這個至少三次upvote。簡單,乾淨,恰到好處。 – RekindledPhoenix 2013-10-08 16:46:12
太棒了!一旦你指出它就很容易! – ganders 2014-11-07 19:30:02
非常感謝你,[這裏](http://stackoverflow.com/a/30151780/2218697)我使用了'ViewBag',因爲它處理null,並在佈局中使用了'@ ViewBag.Title',並且工作得很好,但'如果標題爲空,@ RenderSection'會拋出運行時未定義的錯誤 – stom 2015-05-10 13:10:33