Asp.net-Mvc-5

使用 MVC-5 在查看頁面中添加元標記

  • April 21, 2014

我在 _Layout.cshtml 母版頁中有兩個元標記,現在我想在someone.cshtml 視圖頁面中添加元標記。

我也嘗試使用此程式碼

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

放入someone.cshtml之類的 @section metatags { <meta ... /> }

但沒有獲得成功。

並嘗試添加元標記 jquery 但效果不佳。

我找到了一種現在可行的方法。

此解決方案主要在多個母版頁時使用。

在控制器/操作中分配該視圖所需的任何元資訊。

ViewBag.Title = "some title";
ViewBag.MetaDescription = "some description";

在視圖或母版頁中,獲取該視圖所需的任何元資訊。

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

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

它應該工作。

這是我的母版頁_Layout.cshtml

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

這是index.cshtml文件

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

<div>Page content</div>

結果

<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>

引用自:https://stackoverflow.com/questions/23196597