我有一个包含多个 View 组件的布局,它们都使用相同的 View 模型和 Controller
那么我该怎么做才能在它们之间共享相同的 View 模型实例呢?
这是我的布局:
<!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>
你差不多明白了:
// inside View Component
public async Task<IViewComponentResult> InvokeAsync(SharedModel sharedmodel) { ... }
内部 *.cshtml:
@model MyApp.Models.SharedModel
...
<article id="main-content-article">
@await Component.InvokeAsync("Cover", new { sharedmodel = model } )
</article>
请注意,匿名类中的属性与 InvokeAsync
方法中的参数同名。所有这些都清楚地记录在 documentation 中尽管。
我是一名优秀的程序员,十分优秀!