2

I have a layout that has several view components, all of them are using the same viewmodel and the controller

so how can I do to share the same viewmodel instance between all of them?

this is my layout:

<!DOCTYPE html>
<html lang="es">
<head prefix="og: http://ogp.me/ns#">
    @await Component.InvokeAsync("Metadata", Share-Model)
</head>
<body>
    @await Component.InvokeAsync("Header", Share-Model)
    <article id="main-content-article">
        @await Component.InvokeAsync("Cover", Share-Model)
    </article>
    <section id="rest-fold-content">
        @RenderBody()
        <footer id="main-footer">
            @await Component.InvokeAsync("Footer")
        </footer>
    </section>

</body>
</html>
pedrommuller
  • 15,741
  • 10
  • 76
  • 126

1 Answers1

6

You got it almost:

// inside View Component
public async Task<IViewComponentResult> InvokeAsync(SharedModel sharedmodel) { ... }

Inside *.cshtml:

@model MyApp.Models.SharedModel
...
    <article id="main-content-article">
    @await Component.InvokeAsync("Cover", new { sharedmodel = model } )
</article>

Please note that the property in the anonymous class has the same name as the parameter in the InvokeAsync method. It's all clearly documented in the documentation though.

Tseng
  • 61,549
  • 15
  • 193
  • 205
  • I'm using these components in a layout, do you thinks is approach is still valid for dotnet core? http://stackoverflow.com/questions/13225315/pass-data-to-layout-that-are-common-to-all-pages/13231752#13231752 – pedrommuller Jul 21 '16 at 17:19