You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 7.0如何向视图组件传递静态参数

向ASP.NET Core视图组件传递静态文本字符串的正确方式

我负责UI开发,想要创建一个能在所有页面全局复用的HTML模板,现在需要了解如何向视图组件传递静态文本字符串,我的代码如下:

1. 视图组件类代码(ViewComponent/PageHeaderViewComponent.cs)

public class InvokeRequest
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public string E { get; set; }
}

[ViewComponent(Name = "PageHeader")]
public class PageHeaderViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(InvokeRequest request)
        
    {
        return View("Index", request);
    }
}

2. 视图组件模板代码(Views/Shared/Components/PageHeader/Index.cshtml)

你的模板代码存在模型类型错误:当前@model string无法匹配传递的InvokeRequest对象,会导致渲染时抛出异常。修正后的代码如下:

@model InvokeRequest
<!-- 注意:如果InvokeRequest在特定命名空间下,需完整引用,例如:@model YourProjectNamespace.ViewComponent.InvokeRequest -->

<div id="SomeTemplateTest">
    <p>@Model.A</p>
    <h1>@Model.B</h1>
    <h1>@Model.C</h1>
    <h1>@Model.D</h1>
    <!-- 可按需新增E的渲染 -->
    <p>@Model.E</p>
</div>

3. 布局页调用代码(Views/Shared/_Layout.cshtml)

<body>
...
@await Component.InvokeAsync("PageHeader", new InvokeRequest(){ 
    A = Model.A, 
    B = "静态标题文本", <!-- 直接传递静态字符串 -->
    C = Model.C, 
    D = Model.D, 
    E = "2" <!-- 静态值转字符串传递 -->
})
...
</body>

关键说明

  • 静态文本传递核心方式:调用组件时,直接给InvokeRequest的属性赋值静态字符串(如示例中的B = "静态标题文本"、E = "2")即可完成静态文本传递。
  • 强类型模型优势:定义InvokeRequest强类型模型能提供编译时错误检查,避免拼写错误,非常适合全局复用的视图组件场景。
  • 简化调用(可选):若无需强类型校验,也可直接传递匿名对象,无需定义InvokeRequest类:
@await Component.InvokeAsync("PageHeader", new { 
    A = Model.A, 
    B = "静态文本", 
    C = Model.C, 
    D = Model.D, 
    E = "2" 
})

此时视图模板的模型需改为@model dynamic,但不推荐全局复用组件使用这种方式,不利于长期维护。

内容的提问来源于stack exchange,提问作者Kelvin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:32:07