Razor Engine - SEO Meta标签

问题描述:

我需要在每个页面上放置独特的描述和关键字元标签。试过这个。但它没有点击。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"; 
} 
+2

我想这个至少三次upvote。简单,干净,恰到好处。 – RekindledPhoenix 2013-10-08 16:46:12

+0

太棒了!一旦你指出它就很容易! – ganders 2014-11-07 19:30:02

+0

非常感谢你,[这里](http://stackoverflow.com/a/30151780/2218697)我使用了'ViewBag',因为它处理null,并在布局中使用了'@ ViewBag.Title',并且工作得很好,但'如果标题为空,@ RenderSection'会抛出运行时未定义的错误 – stom 2015-05-10 13:10:33

您需要发出在布局网页<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" /> 
} 
+0

使用'@if(ViewBag.Description!= null)'的原因是什么? – 2016-12-24 11:16:25

+0

因此,如果不需要,它不会添加标签。 – 2017-01-24 13:44:48