Q: I'm having problems setting meta tags in my @ Page directive like in your article. My graphics designers don't understand code, but they can deal with page directives. It would be great to have this approach working. Do you have an example I can download?
A: Download the example web project.
The project contains four web forms, one class file, and one master page. The class file defines a base class for all web forms, and looks like the following.
The article was demonstrating how to use a base class from a web form with inline code. We need a slightly different approach for web forms using code-beside.
This project has four combinations:
To set the MetaKeywords property from the @ Page directive with code-beside, you'll need the following:
Notice the use of the CodeFileBaseClass attribute, which is needed for ASP.NET to pick up the Metakeywords property at the time it generates code. The other required step is to make sure the class in the code-beside file derives from the base class we defined.
You'll still have red squiggly lines in the @ Page directive. Visual Studio is overly zealous about validating the @ Page directive, and won't like the Metakeywords attribute. This is just a validation error and doesn't prevent the web form from compiling and executing. ASP.NET will generate the right code the words inside the MetaKeywords attribute will render into the HTML output.
This approach isn't limited to just meta tags, we could give the base class other public properties that we can set in the @ Page directive and use at runtime.
Hope that helps...
Comments
You're the man, the CodeFileBaseClass was the ticket to success there!
Thanks,
Eric
I have a <h1>page description goes here</h1> tag in my master page. In the Page_PreRender event I have access to the Title shouldn't I have access to my MetaDescription property as well? My system does not work. What am I missing?
protected void Page_PreRender(object sender, EventArgs e)
{
Page.Header.Title = string.Format(HEADER_PREFIX, Page.Header.Title);
LiteralWebPageDescription = Page.Header.MetaDescription;
}
I loved the idea of using the page directives so implemented them in a recent project. The code seems to work locally but when i post to the server, I consistently receive the following error:
CS0117: 'ASP.commercial_specialty_door_repair_aspx' does not contain a definition for 'MetaKeywords'
However, on most pages, if I refresh the page one or two times, it will then work just fine. I am guessing the main difference is that i am using Master pages where the master page is inheriting the base class.
Have you had any issues with this in master page scenarios?
Thanks,
David