使用控制器操作将元描述标记添加到 html head?

POI*_*OIR 2 asp.net-mvc meta-tags

如何<meta name="description">使用控制器操作向 html head 中的元描述标记添加值?

    public ActionResult Details(int id = 0, string name = "")
    {

        Category category = db.Categories.Find(id);

        string seodescription = string.Empty;

        switch (id)
        {
            case 1: { seodescription = "1"; break; }
            case 2: { seodescription = "2"; break; }
            case 3: { seodescription = "3"; break; }
            case 4: { seodescription = "4"; break; }
            case 5: { seodescription = "5"; break; }
            case 8: { seodescription = "6"; break; }
            default: {seodescription = string.Empty; break;}
        }

        if (seodescription != string.Empty)
        {
             // here
        }

   }
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以在ViewBag中传递描述:

ViewBag.MetaDescription = "Description to use";
Run Code Online (Sandbox Code Playgroud)

并在视图中渲染 <meta> 标记。

由于您可能正在使用布局并且元标记位于标题中,因此您应该将代码放在布局页面中:

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