Razor引擎-SEO元标签

20

我需要为每个页面放置唯一的描述和关键词元标签。尝试了这个方法,但它没有起作用。

@{
    ViewBag.Title = "Title";
    ViewBag.Description = "Test";
    ViewBag.Keywords = "Test1, Test2, Test3";
}

我该如何在MVC 3 Razor引擎中放置meta标签?

3个回答

56
在布局中,您可以定义一个“section”(部分):
<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";
}

3
我至少想给这个点赞三次。简单、清晰、直接。 - RekindledPhoenix
非常感谢,在这里我使用了ViewBag,因为它可以处理空值,并且只需在布局中使用@ViewBag.Title即可正常工作,但是如果Title为空,则@RenderSection会抛出运行时未定义的错误。 - Shaiju T

26

您可以像之前那样操作,但是您必须在_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) 的原因是什么? - neda Derakhshesh
如果不需要,它就不会添加标签。 - Carles Company

1

您需要在布局页面中发出使用这些值的<meta>标签。
您可以通过编写@ViewBag.Description来获取标签中的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接