Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Razor Meta Description / Keywords

What is the simplest way of getting meta description / keywords onto my _Layout page? Something similar to how you get the page Title would be nice. Such as

<title>@ViewBag.Title</title>
<meta name="keywords" content='@ViewBag.Keywords'/>
<meta name="description" content='@ViewBag.Description'/>

My view would look something like:

@{
    ViewBag.Title = "Contact Me";
    ViewBag.Keywords = "My, keyword, list, etc";
}
like image 364
Judder1981 Avatar asked Feb 26 '23 03:02

Judder1981


2 Answers

Your view should not be responsible of that (do not add logic to views). Instead, it's the action method that should specify meta information.

Check my answer here: asp.net mvc - strategy for including SEO information such as meta keywords and descriptions

The answer still apply, although you should use ViewBag instead of ViewData.

like image 65
jgauffin Avatar answered Feb 27 '23 16:02

jgauffin


I wrote a custom mvc3 metatag helper that would do just that. It works with resources when using multiple languages (if required):

public enum MetatagType
{
    /// <summary>
    /// Used for Title meta tag.
    /// </summary>
    Title,

    /// <summary>
    /// Used for Description and keyword meta tag.
    /// </summary>
    MetaData,

    /// <summary>
    /// Used for noindex, nofollow meta tag.
    /// </summary>
    Robots
}

public static class MetatagExtensions
    {
        #region Public Methods

        public static MvcMetaTag MetaTag(this HtmlHelper helper, MetatagType metaType)
        {
            return new MvcMetaTag(helper, metaType);
        }

        #endregion

        public sealed class MvcMetaTag
        {
            #region Constructors and Destructors

            public MvcMetaTag(HtmlHelper helper, MetatagType metaType)
            {
                this.Helper = helper;
                this.MetaType = metaType;
            }

            #endregion

            #region Properties

            /// <summary>
            /// Gets or sets Helper.
            /// </summary>
            private HtmlHelper Helper { get; set; }

            /// <summary>
            /// Gets or sets MetaType.
            /// </summary>
            private MetatagType MetaType { get; set; }

            #endregion

            #region Public Methods

            public MvcHtmlString Render()
            {
                var sb = new StringBuilder();
                if (this.Helper.ViewContext.RouteData.DataTokens.ContainsKey("area"))
                {
                    sb.Append(this.Helper.ViewContext.RequestContext.RouteData.DataTokens["area"].ToString().ToLower());
                    sb.Append('_');
                }
                sb.Append(this.Helper.ViewContext.RequestContext.RouteData.Values["controller"].ToString().ToLower());
                if (this.Helper.ViewContext.RequestContext.RouteData.Values["action"].ToString().ToLower() != "index")
                {
                    sb.Append('_');
                    sb.Append(this.Helper.ViewContext.RequestContext.RouteData.Values["action"].ToString().ToLower());
                }

                var resourcemng = SharedResources.ResourceManager;
                var meta = new StringBuilder();
                switch (this.MetaType)
                {
                    case MetatagType.MetaData:
                        meta.AppendLine(
                            String.Format(
                                "<meta name=\"description\" content=\"{0}\" />",
                                this.Helper.ViewData["Description"]
                                ?? resourcemng.GetString(string.Format("md_{0}", sb)) ?? string.Empty));
                        meta.AppendLine(
                            String.Format(
                                "<meta name=\"keywords\" content=\"{0}\" />",
                                this.Helper.ViewData["Keywords"]
                                ?? resourcemng.GetString(string.Format("mk_{0}", sb)) ?? string.Empty));
                        break;
                    case MetatagType.Robots:
                        meta.AppendLine(
                            String.Format(
                                "<meta name=\"robots\" content=\"{0}\" />",
                                this.Helper.ViewData["Robots"]
                                ?? resourcemng.GetString(string.Format("mr_{0}", sb)) ?? string.Empty));
                        break;
                    case MetatagType.Title:
                        meta.AppendLine(
                            (string)(this.Helper.ViewData["Title"]
                                     ?? resourcemng.GetString(string.Format("mt_{0}", sb)) ?? string.Empty));
                        break;
                }

                return new MvcHtmlString(meta.ToString());
            }

            #endregion
        }
    }

Then in your _Layout.cshtml file you use it like so: ...

    <head runat="server">
        <title>@Html.MetaTag(MetatagType.Title).Render()</title>

@Html.MetaTag(MetatagType.MetaData).Render()

...

In your resources file you should add the following (Controller-> Home, Action->Index):

mt_home -> homepage Title

md_home -> homepage description here

mk_home -> homepage keywords

for about page mt_home_about -> about title etc.

You also have an option to overwrite metadata from resources in specific views like so Index.cshtml:

@{
    ViewBag.Title = "New TITLE";
    ViewBag.Description = "New Description";    
}
like image 24
ShaneKm Avatar answered Feb 27 '23 16:02

ShaneKm