2011-04-28 54 views
3

嗨我不知道這是否是正確的方法,但我想建立一個網站與動態元標記。在asp.net mvc元標記的正確方法3

某些元標記是硬編碼到系統,但有些需要動態加載,我應該能夠在相應的操作中設置它們。

所以我需要一個元標籤建立邏輯,像一個局部視圖,甚至是一個子動作,但我不確定正確的方法。

我想它的工作,即使有任何關於它的行動,(它應該加載,則默認)

將在layout.cshtml一個childaction是最好的方法?

回答

2

你可以嘗試爲此使用ViewBag對象。我將使用字典,但如果元標記不是那種動態的,你可能會使用更強的類型。

在你的(2鹼)控制器構造函數中,創建一個字典在ViewBag舉行的meta標籤:

/* HomeController.cshtml */ 
public HomeController() 
{ 
    // Create a dictionary to store meta tags in the ViewBag 
    this.ViewBag.MetaTags = new Dictionary<string, string>(); 
} 

然後設定一個meta標籤在你的行動,只是添加到詞典]:

/* HomeController.cshtml */ 
public ActionResult About() 
{ 
    // Set the x meta tag 
    this.ViewBag.MetaTags["NewTagAddedInController"] = "Pizza"; 
    return View(); 
} 

或者,你甚至可以在視圖中添加它(.cshtml):

/* About.cshtml */ 
@{ 
    ViewBag.Title = "About Us"; 
    ViewBag.MetaTags["TagSetInView"] = "MyViewTag"; 
} 

最後,你的佈局頁面,你可以檢查字典的存在,並通過輸出每個條目的元標記循環:

/* _Layout.cshtml */ 
<head> 
    <title>@ViewBag.Title</title> 
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> 
    @if (ViewBag.MetaTags != null) 
    { 
     foreach (var tag in ViewBag.MetaTags.Keys) 
     { 
      <meta name="@tag" content="@ViewBag.MetaTags[tag]" /> 
     } 
    } 
</head> 
相關問題