我们可以在 asp.net mvc 中具有主布局的视图中创建元标记吗

发布于 2024-12-25 13:11:25 字数 185 浏览 3 评论 0原文

在我的一个观点中,我需要为社交插件创建一些元标签,但找不到一种方法来做到这一点。

由于元标记仅对应于这一视图,因此在主布局中对它们进行编码,然后在视图中设置值似乎并不正确。

有什么方法可以在视图中创建元标记,然后将其添加到母版布局的头部部分。或者我应该将它们添加到主布局中,然后设置它们的值,就像我对描述和关键字所做的那样。

In one of my views, I need to create some meta tags for social plugins, but couldn't find a way to do so.

Since the meta tags corresponds to this one view only, coding them in master-layout and then setting the values in View doesn't seem right.

Is there any way that I can create the meta tags in a View which can then be added to the head section of mater-layout. Or should i just add them to the master-layout and then set there values, like I do for description and keywords.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧故 2025-01-01 13:11:25

您可以使用razor 部分来执行此操作。我们对特定于视图的脚本和 CSS 执行此操作,但您也可以将模式应用于元标记。

在布局中:

<head>
    <meta (global meta tag) ../>
    @if (IsSectionDefined("HeadMeta"))
    {
        @RenderSection("HeadMeta")
    }
</head>

在部分视图中:

@section HeadMeta
{
    <meta (view-specific social meta tag) ../>
}

You can do this with razor sections. We do this for view-specific scripts and css, but you can apply the pattern for meta tags too.

In layout:

<head>
    <meta (global meta tag) ../>
    @if (IsSectionDefined("HeadMeta"))
    {
        @RenderSection("HeadMeta")
    }
</head>

In partial view:

@section HeadMeta
{
    <meta (view-specific social meta tag) ../>
}
颜漓半夏 2025-01-01 13:11:25

您唯一能做的就是使用与描述和关键字相同的方法。然后在主布局中编码,然后在视图中设置值就可以了,因为它们的位置实际上在布局中,并且它们的值取决于显示的视图。

The only thing you can do is to use the same approach you use for description and keywords. And coding then in master-layout and then setting the values in View is OK, because their place is actually in the layout, and their value depends on the view that is shown.

暮光沉寂 2025-01-01 13:11:25

使用 ViewBag

您还可以在主布局中

<meta name="description" content="@ViewBag.MetaDescription" />

在您的部分布局中

@{
ViewBag.MetaDescription = "My meta description string";
}

:缺点是您必须在每个部分中创建此 ViewBag 值(或执行 if(ViewBag.Metadescription != null) 检查)

You can also use ViewBag

In your master layout:

<meta name="description" content="@ViewBag.MetaDescription" />

In your partial:

@{
ViewBag.MetaDescription = "My meta description string";
}

Downside is that you have to create this ViewBag value in every partial (or do an if(ViewBag.Metadescription != null) check)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文