ASP.Net MVC: how to dynamically generate meta tag based on url content?

Here's the idea:

When a user wants to see / controller / action, I want the page to have a robots meta tag with its value set to all. When does a user want to see / controller / action? Sort = hot & page = 2 (ie has a query string), then I want the page to have a "robots" meta tag with its value set to "noindex". Of course, this is just an example and it could be another tag for this question to exist.

At what stage in the MVC architecture can I place a hook so that the view generates the tag I want on the master page?

0


source to share


1 answer


I am doing something like this for generating page titles and it works well. Place your tag on your homepage as usual:

<%= Html.Encode(ViewData["Title"]) %>

      

Then subclass ActionFilterAttribute

and override OnActionExecuting

. From there, you get access to the controller context and can set your browsing data anytime you like.



public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewData["title"] = "whatever";
    }

      

the last step is to set the attributes of your controllers that you want to use in the filter context. You can inherit from the base controller if you want to add an attribute to all classes. There are also overloads if you want to pass parameters. In my application. I am actually passing the title of the page.

Hope it helps.

+2


source







All Articles