簡體   English   中英

如何根據查詢字符串參數在母版頁上添加元標記

[英]How to add meta tags on master page dependent on query string parameter

如何添加根據瀏覽器的查詢字符串參數更改的元標記?

例如,在我的博客站點上,從數據庫中讀取了博客,示例博客為http://www.example.com/blog/blog.aspx?ID=32

我希望針對不同的博客文章自定義meta標簽,這些文章均從blog.aspx文件中讀取。

以下文章為我提供了一個思路,但是如何實現一條語句來讀取查詢字符串參數?

如何在ASP.Net MVC 2的母版頁上添加元標記

如何在ASP.NET MVC中傳遞頁面的元標記?

通常,在這種情況下,我將為所有視圖模型提供基類 ,例如:

public abstract BasicViewModel
{
    public List<string> MetaTags {get; set; }
}

現在,如果我們假設站點中的每個視圖模型都繼承自該視圖模型,則我們可以在布局中使用強類型的視圖模型。

@model BasicViewModel
<html>
    <head>
       <!-- Render meta tags here from view model -->
    </head>
    @RenderBody()
</html>

我已經忽略了一個事實,即Meta標記可能比字符串更復雜,但是您明白了。

在您的控制器中,只要他們的視圖模型是從此派生的-您就可以隨意將任何元標記添加到視圖模型。 這也涉及頁面標題和每個頁面的其他通用內容(例如,Google Analytic帳戶詳細信息!)。

為了獲得動態的meta關鍵字和描述,這是我使用動作過濾器的解決方案。

創建一個動作過濾器並處理其OnActionExecuted方法-

public class MetaDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var key = filterContext.RouteData.Values["id"];

        // using key get proper keywords and description for page

        filterContext.Controller.ViewBag.MetaKeywords = "1, 2, 3";
        filterContext.Controller.ViewBag.MetaDescription = "This is new description";
    }
}

然后使用元數據屬性標記您的控制器操作-

    [MetaData]
    public ActionResult Index(string id)
    {
        return View();
    }

如果id是您期望動作執行的動態查詢字符串,則在動作執行結束時調用OnActionExecuted時,將使用RouteData在動作過濾器中訪問id。

例如,假設您到達URL- http://localhost:5738/Blog/Index/123 ,則將以這種方式在操作過濾器中訪問http://localhost:5738/Blog/Index/123

在此處輸入圖片說明

然后,基於id值,您可以在ViewBag中設置適當的關鍵字和描述。 然后從Viewbag,你可以在獲取值_Layout.cshtml如下圖所示-

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

因此,在呈現頁面時,您的元關鍵字和描述將反映如下-

<meta name="keywords" content="1, 2, 3">
<meta name="description" content="This is new description"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM