I know that there are duplicate questions on this, but I haven't found the answer yet. So please help. :)
I am trying to change dynamically the meta tag content which is found in my layout view using back-end codes. This is so Facebook can crawl the data when the page is being shared. And until now I am unsuccessful.
It's hard because MVC does not let Viewbag be read in the Layout view. Also, my Layout view is not in the shared folder. And I can't just simply transfer it there.
UPDATE: The meta tags are already hard-coded in the Layout View. I just need to update the value of the content=""
in the meta tags dynamically.
Here are the approaches I have tried:
Viewbag: Returns null
Child View
ViewBag.Meta1 = model.JobTitleHeading;
ViewBag.Meta2 = model.JobTitleDescription;
Layout View
var metaTag1 = ViewBag.Meta1;
var metaTag2 = ViewBag.Meta2;
Javascript: Updates the Meta Tag but Facebook can't crawl the updated data because JS kicks in after page load.
$("meta[property='og\\:title']").attr("content", jl1);
$("meta[property='og\\:description']").attr("content", jl2);
HtmlMeta: Returns null
HtmlMeta metaTitle = new HtmlMeta();
HtmlMeta metaDescription = new HtmlMeta();
var placeHolderCheck = metaTitle.FindControl("LayoutPlaceHolder");
if (placeHolderCheck != null)
{
metaTitle.Attributes.Add("property", "og:title");
metaTitle.Content = model.Data1;
Page.Header.Controls.Add(metaTitle);
metaDescription.Attributes.Add("property", "og:description");
metaDescription.Content = model.Data2;
Page.Header.Controls.Add(metaDescription);
}
HttpContext Session: Updates Meta Tag but session expires. And on first page load the session is null, then on the second page load, the session contains the value from the first session, thus a logical error.
Child view:
this.ViewContext.HttpContext.Session["MetaTitle"] = model.Data1;
Layout view:
string metaHeading = string.Empty;
metaHeading = (string)HttpContext.Current.Session["MetaTitle"];
I also tried HttpContext.Current.Items, TempData, PageData, but still get null results.
I just really want to pass the data from the Controller to the View and then to the Layout view. Or if possible, pass the data from Controller to the Layout view.
Thanks.