开发者

Correct approach of meta tagging in asp.net mvc 3

Hi I'm not sure if this is the correct approach, but I would like t开发者_如何转开发o build a site with dynamic meta tags.

Some meta tags are hard coded to the system, but some needs to load dynamically and I sould be able to set them in the corresponding action.

So I would need a meta tag building logic with something like a partial view, or even a child action, but I'm not sure about the correct approach.

I would like it to work even when there is nothing about it in an action, (it should load the default then)

Would a childaction in the layout.cshtml be the best approach?


You could try using the ViewBag object for this. I'll use a Dictionary, but you might be able to use something more strongly-typed if the meta tags aren't that dynamic.

In your (Base?)Controller constructor, create a dictionary in the ViewBag to hold the meta tags:

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

Then to set a meta tag in your action, just add to the dictinary:

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

Alternatively, you could even add it in the view (.cshtml):

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

Finally, in your Layout page, you can check for the presence of the dictionary, and loop through outputting a meta tag for each entry:

/* _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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜