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

如何在ASP.NET MVC应用中构建模块化Razor组件?

在ASP.NET MVC里实现可复用嵌套Razor组件的方法

先把项目配置弄对

要让MVC项目支持Razor组件,得先完成这两项配置:

  • 在Program.cs中添加组件服务:
    builder.Services.AddRazorComponents()
        .AddServerComponents();
    
  • 在_Layout.cshtml的</body>标签前,引入Blazor服务器端脚本:
    <script src="_framework/blazor.server.js"></script>
    

编写可复用的组件

1. 先创建Icon组件

新建Icon.razor文件,接收图标样式类名参数:

@* Icon.razor *@
<i class="@IconClass"></i>

@code {
    [Parameter]
    public string IconClass { get; set; } = "";
}

2. 创建Button组件并嵌套Icon

在Button组件里直接用组件标签引用Icon即可,不需要用<component>标签——这才是组件内部复用的正确方式:

@* Button.razor *@
<a href="@Link" class="button">
    @if (!string.IsNullOrEmpty(IconClass))
    {
        <Icon IconClass="@IconClass" />
    }
    @Text
</a>

@code {
    [Parameter]
    public string Text { get; set; } = "";
    
    [Parameter]
    public string Link { get; set; } = "#";
    
    [Parameter]
    public string IconClass { get; set; } = "";
}

在MVC视图中使用Button组件

回到index.cshtml,用<component>标签引入Button组件并传递参数:

@* index.cshtml *@
<component type="typeof(Button)" render-mode="ServerPrerendered" param-Text="Click me" param-Link="/" param-IconClass="fa-solid fa-pen-to-square" />

关键说明

  • Razor组件之间的复用,直接写组件标签(比如<Icon />)即可,<component>仅用于在MVC的cshtml视图文件中引入Razor组件,组件内部不要使用它。
  • 建议把所有Razor组件放在项目的Components目录下,方便框架自动识别。
  • 保持render-mode="ServerPrerendered",既能实现服务器端预渲染HTML,又能保留组件的交互能力。

这样就能实现你想要的模块化结构:Button组件嵌套Icon组件,最终渲染出带图标的按钮HTML。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:48:34