.Net MVC - Pass data from child view to layout vie

2019-09-07 08:47发布

问题:

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.

回答1:

Have you looked into defining sections? Define a section in your page, set the data in there and make sure the section is specified in the Layout page where it should be, I haven't tried this personally, but from what you are saying, it should make sense.

@RenderSection("MetaRender",false)

and then in view, use

@section MetaRender{...}

Have you tried that yet?



回答2:

Use in Layout View :

  <meta name="mymeta1" content="@ViewBag.Meta1" />
  <meta name="mymeta2" content="@ViewBag.Meta2" />

It's working either you update values in VIEW or in ACTION.

ViewBag.Meta1 = "xyz";
ViewBag.Meta2 = "abc";