使用MVC-5在View页面中添加Meta标签

Jat*_*iya 13 nopcommerce asp.net-mvc-5

我在_Layout.cshtml母版页中有两个元标记,现在我想在someone.cshtml视图页面中添加元标记.

我也尝试使用此代码

放入_layout.cshtml母版页 @RenderSection("metatags",false);

放入someone.cshtml就好 @section metatags { <meta ... /> }

但没有成功.

并尝试添加元标记jquery但没有正常工作.

mez*_*tou 41

它应该工作.

这是我的母版页 _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @RenderSection("metatags", false)
    <title>My ASP.NET Application</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是index.cshtml文件

@section metatags
{
    <meta name="test" content="test"/>
    <meta name="test2" content="test"/>
}

<div>Page content</div>
Run Code Online (Sandbox Code Playgroud)

结果

<html>
<head>
    <meta charset="utf-8">

    <meta name="test" content="test">
    <meta name="test2" content="test">

    <title>My ASP.NET Application</title>
</head>
<body>        

<div>Page content</div>    

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 错误:未定义部分:“元标记”。在_Layout.cshtml中 (2认同)

Jat*_*iya 11

我发现了一种适用于现在的方法.

此解决方案主要用于多个母版页.

在控制器/操作中,为该视图分配所需的任何元信息.

ViewBag.Title = "some title";
ViewBag.MetaDescription = "some description";
Run Code Online (Sandbox Code Playgroud)

在"视图"或"母版"页面中,获取该视图所需的任何元信息.

 @if(ViewBag.MetaDescription != null)
    {
        <meta name="description" content="@ViewBag.MetaDescription" />
    }

    @if(ViewBag.MetaKeywords != null)
    {
        <meta name="keywords" content="@ViewBag.MetaKeywords" />
    }
Run Code Online (Sandbox Code Playgroud)