Assign dynamic data from a webparts codebehind file to HTML Head

Jacob Mallach asked on April 3, 2018 20:51

Hello,

I have some custom code inside a webparts codebehind file that is making a third party api call. Once connecting to the third party api, the code stores the returned data in some variables, loops through that data and assigns the value to html via the .ascx file. This all works swimmingly with one exception. I need to assign some of this data to the page types html <head> for social open graph i.e.,<meta> properties. This needs to happen on the backend prior to page load. Is there a way to pipe the returned data from the codebehind file to the <meta> properties?

Thanks for the help.

Recent Answers


Jacob Mallach answered on April 3, 2018 21:01 (last edited on April 3, 2018 21:07)

0 votesVote for this answer Mark as a Correct answer

Rui Wang answered on April 3, 2018 21:22 (last edited on April 3, 2018 21:24)

Kentico has a builtin webpart Head HTML (\CMS\CMSWebParts\General\headhtml.ascx.cs) which renders HTML into the <head>. You can learn from that file.

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    if (StopProcessing)
    {
        // Do nothing
    }
    else
    {
        Page.Header.Controls.Add(new LiteralControl(HTMLCode));
    }
}
1 votesVote for this answer Mark as a Correct answer

Jacob Mallach answered on April 3, 2018 23:22

Hi Rui,

Thanks for the feedback. I'm not seeing any documentation online describing how to pull data from a webpart controller into this headHtml webpart. Can you help with that? As an alternative approach, is it possible to store the data in a macro? And then call it up at will?

Thanks for the help.

0 votesVote for this answer Mark as a Correct answer

Rui Wang answered on April 3, 2018 23:32

The HeadHtml webpart has a field called "HTMLCode" and the get method in that CS pulls what developer would type in when the webpart is dropped into a template.

In your case, you are populating the HTML in code behind, so you can add the above code into your custom web part. Then build the HTML for the meta into a string (e.g. myHTMLHeader). Then you can populate it in this line.

Page.Header.Controls.Add(new LiteralControl(myHTMLHeader));

0 votesVote for this answer Mark as a Correct answer

Jacob Mallach answered on April 4, 2018 19:08 (last edited on April 4, 2018 19:10)

Hi Rui - Thanks, this isnt exactly what I'm after, but I do see value in your suggestion. Especially with the absence of posting the source code. Cheers!

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.