c# - 在 dotnet 核心中的 View 组件之间共享模型

标签 c# razor asp.net-core asp.net-core-mvc

我有一个包含多个 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 中尽管。

关于c# - 在 dotnet 核心中的 View 组件之间共享模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493968/

相关文章:

asp.net-mvc-3 - MVC3 - 使用 Razor 有条件地添加 id 元素

c# - ASP.NET Core DI 构造函数与 RequestServices

c# - ReSharper 9 添加菜单项操作不起作用

c# - 匿名函数委托(delegate) yield

c# - 从托管C#代码中调用非托管C++代码以生成脱机域加入Blob

c# - 页面在 localhost 上加载,但不在 Azure 网站中加载 - 错误 500

c# - 在 C# 中将文件夹从一个驱动器移动到另一个驱动器

c# - Asp.Net Mvc Core 中的无 session Controller

c# - Microsoft.AspNetCore.App - 版本控制/是否应该在非 ASP.NET 类库中引用它?

c# - 使用datagridview C#更新数据库中的数据