我需要为每个页面放置唯一的描述和关键词元标签。尝试了这个方法,但它没有起作用。
@{
ViewBag.Title = "Title";
ViewBag.Description = "Test";
ViewBag.Keywords = "Test1, Test2, Test3";
}
我该如何在MVC 3 Razor引擎中放置meta标签?
我需要为每个页面放置唯一的描述和关键词元标签。尝试了这个方法,但它没有起作用。
@{
ViewBag.Title = "Title";
ViewBag.Description = "Test";
ViewBag.Keywords = "Test1, Test2, Test3";
}
我该如何在MVC 3 Razor引擎中放置meta标签?
<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";
}
您可以像之前那样操作,但是您必须在_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您需要在布局页面中发出使用这些值的<meta>
标签。
您可以通过编写@ViewBag.Description
来获取标签中的值。
ViewBag
,因为它可以处理空值,并且只需在布局中使用@ViewBag.Title
即可正常工作,但是如果Title为空,则@RenderSection
会抛出运行时未定义的错误。 - Shaiju T