【问题标题】:Razor Engine - SEO Meta tagsRazor 引擎 - SEO 元标签
【发布时间】:2011-07-28 17:24:50
【问题描述】:

我需要为每个页面放置唯一的描述和关键字元标记。试过这个。但它没有点击。

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

如何在 MVC 3 Razor 引擎中放置元标记?

【问题讨论】:

    标签: asp.net-mvc-3 seo razor meta-tags


    【解决方案1】:

    您可以照常做,但您必须在 _Layout.cshtml 中链接它们。将此添加到您的 _Layout.cshtml 的 <head> 部分:

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

    【讨论】:

    • 使用@if(ViewBag.Description!=null)的原因是什么?
    • 所以不需要的时候不加标签。
    【解决方案2】:

    在布局中你可以定义一个部分:

    <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";
    }
    

    【讨论】:

    • 我想对此至少投三票。简单、干净、切中要害。
    • 非常感谢,here 我使用了ViewBag,因为它处理 null 并且只在布局中使用了 @ViewBag.Title 并且效果很好,但是如果 Title 为 null,@RenderSection 会抛出运行时未定义错误
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多