开发者

ASP.NET MetaTags from database

开发者 https://www.devze.com 2023-03-22 00:15 出处:网络
I\'m developing a web site in which the site manager can change dinamically the MetaTags for the web site in a cms, storing those MetaTags in a MySql database.

I'm developing a web site in which the site manager can change dinamically the MetaTags for the web site in a cms, storing those MetaTags in a MySql database.

In the public master.page, in the Page_Load event, I get those MetaTags from the database

sTitle = get_from_data_base();

using (HtmlMeta mTag = new HtmlMeta())
{ 
    mTag .Name = "Title"; 
    mTag .Content = sTitle; 
    Page.Header.Controls.Add(mTag); 
}

The problem is everytime a page loads, the load event of the master.page is loading from database those MetaTags.

How can I keep in 开发者_如何转开发cache or something similar the metatags once they have been loaded so the site doesn't access the database on every request?

How can the site knows when those MetaTags have changed to load them again?

Please, could you provide an example.

Thanks so much.


One of the solutions to do is to load the data once in the global.asax application start event and add the result in application object then in each page you need it, load it from the application object.

When the data is changed in the database, access the application object and update it as well.

If you don't know how to deal with global.asax or application object, i will post code.

void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            string sTitle = get_from_data_base();
            Application.Add("sTitle", sTitle);

        }
        public string get_from_data_base()
        {
            //update this to call the database and get the data
            return "Your data";
        }

In your pages write the following:

string sTitle = Application["sTitle"].ToString();
            using (HtmlMeta mTag = new HtmlMeta())
            {
                mTag.Name = "Title";
                mTag.Content = sTitle;
                Page.Header.Controls.Add(mTag);
            }

While your manage is updating the metatag append the following line

Application["sTitle"] = "You manager entered string";


Finally, after your answers and reading on the Internet I went for the Cache object instead Application object. I have read is better, so my final aproach for this would be to add this on the global class and access this method from my master.pages

    public static MetaTagsDN get_meta_tags()
    {
        MetaTagsDN oTags;

        if (HttpRuntime.Cache["MetaTags"] == null)
        {
            MetaTagsLN ln = new MetaTagsLN();
            oTags = ln.get_metatags();

            HttpRuntime.Cache["MetaTags"] = oTags;
        }
        else
        {
            oTags = (MetaTagsDN)HttpRuntime.Cache["MetaTags"];
        }

        return oTags;
    }

What do you think?

Thanks for helping me...

0

精彩评论

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