Token导航 LogoToken导航TokenDH.com
开发操作浏览器github未标认证来源可访问许可证需确认审计异常

dotnet-blazor-componentsdotnet Blazor 组件

Agent Skill

dotnet-blazor-components 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

423

周安装

18

GitHub Stars

15

下载量

148
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dotnet-blazor-components(dotnet Blazor 组件)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/dotnet-blazor-components
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-blazor-components
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-blazor-components

简介

dotnet-blazor-components 指导 Blazor 组件的生命周期、状态管理和 JS 互操作方法。

  • 适用于复杂交互界面和第三方库集成的开发需求。
  • 提供 EditForm 验证和 QuickGrid 组件的标准实现。
  • 需特别注意 AOT 编译环境下的 JS 互操作限制。
  • 状态管理推荐使用 DI 注入而非浏览器存储。

SKILL.md

dotnet-blazor-components

Blazor component architecture: lifecycle methods, state management (cascading values, DI, browser storage), JavaScript interop (AOT-safe), EditForm validation, and QuickGrid. Covers per-render-mode behavior differences where relevant.

Scope boundary: This skill owns component implementation patterns. Hosting model selection and render mode configuration are owned by [skill:dotnet-blazor-patterns]. Authentication components (AuthorizeView, CascadingAuthenticationState) are owned by [skill:dotnet-blazor-auth].

Out of scope: bUnit testing -- see [skill:dotnet-blazor-testing]. Standalone SignalR hub patterns -- see [skill:dotnet-realtime-communication]. E2E testing -- see [skill:dotnet-playwright]. UI framework selection -- see [skill:dotnet-ui-chooser].

Cross-references: [skill:dotnet-blazor-patterns] for hosting models and render modes, [skill:dotnet-blazor-auth] for authentication, [skill:dotnet-blazor-testing] for bUnit testing, [skill:dotnet-realtime-communication] for standalone SignalR, [skill:dotnet-playwright] for E2E testing, [skill:dotnet-ui-chooser] for framework selection, [skill:dotnet-accessibility] for accessibility patterns (ARIA, keyboard nav, screen readers).


Component Lifecycle

Lifecycle Methods

@code {
    // 1. Called when parameters are set/updated
    public override async Task SetParametersAsync(ParameterView parameters)
    {
        // Access raw parameters before they are applied
        await base.SetParametersAsync(parameters);
    }

    // 2. Called after parameters are assigned (sync)
    protected override void OnInitialized()
    {
        // One-time initialization (runs once per component instance)
    }

    // 3. Called after parameters are assigned (async)
    protected override async Task OnInitializedAsync()
    {
        // Async initialization (data fetching, service calls)
        products = await ProductService.GetProductsAsync();
    }

    // 4. Called every time parameters change
    protected override void OnParametersSet()
    {
        // React to parameter changes
    }

    // 5. Called after each render
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            // JS interop safe here -- DOM is available
        }
    }

    // 6. Async version of OnAfterRender
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("initializeChart", chartElement);
        }
    }

    // 7. Cleanup
    public void Dispose()
    {
        // Unsubscribe from events, dispose resources
    }

    // 8. Async cleanup
    public async ValueTask DisposeAsync()
    {
        // Async cleanup (dispose JS object references)
        if (module is not null)
        {
            await module.DisposeAsync();
        }
    }
}

Lifecycle Behavior per Render Mode

Lifecycle EventStatic SSRInteractiveServerInteractiveWebAssemblyInteractiveAutoHybrid
OnInitialized(Async)Runs on serverRuns on serverRuns in browserServer on first load, browser after WASM cachedRuns in-process
OnAfterRender(Async)Never calledRuns on server after SignalR confirms renderRuns in browser after DOM updateServer-side then browser-side (matches active runtime)Runs after WebView render
Dispose(Async)Called after responseCalled when circuit endsCalled on component removalCalled when circuit ends (Server phase) or on removal (WASM phase)Called on component removal

Gotcha: In Static SSR, OnAfterRender never executes because there is no persistent connection. Do not place critical logic in OnAfterRender for Static SSR pages.


State Management

Cascading Values

Cascading values flow data down the component tree without explicit parameter passing.

<!-- Parent: provide a cascading value -->
<CascadingValue Value="@theme" Name="AppTheme">
    <Router AppAssembly="typeof(App).Assembly">
        <!-- All descendants can receive AppTheme -->
    </Router>
</CascadingValue>

@code {
    private ThemeSettings theme = new() { IsDarkMode = false, AccentColor = "#0078d4" };
}
<!-- Child: consume the cascading value -->
@code {
    [CascadingParameter(Name = "AppTheme")]
    public ThemeSettings? Theme { get; set; }
}

Fixed cascading values (.NET 8+): For values that never change after initial render, use IsFixed="true" to avoid re-render overhead:

<CascadingValue Value="@config" IsFixed="true">
    <ChildComponent />
</CascadingValue>

Dependency Injection

// Register services in Program.cs
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddSingleton<AppState>();

// Inject in components
@inject IProductService ProductService
@inject AppState State

DI lifetime behavior per render mode:

LifetimeInteractiveServerInteractiveWebAssemblyInteractiveAutoHybrid
SingletonShared across all circuits on the serverOne per browser tabServer-shared during Server phase; per-tab after WASM switchOne per app instance
ScopedOne per circuit (acts like per-user)One per browser tab (same as Singleton)Per-circuit (Server phase), per-tab (WASM phase) -- state does not transfer between phasesOne per app instance (same as Singleton)
TransientNew instance each injectionNew instance each injectionNew instance each injectionNew instance each injection

Gotcha: In Blazor Server, Scoped services live for the entire circuit duration (not per-request like in MVC). A circuit persists until the user navigates away or the connection drops. Long-lived scoped services may accumulate state -- use OwningComponentBase<T> for component-scoped DI.

Browser Storage

// ProtectedBrowserStorage -- encrypted, per-user storage
// Available in InteractiveServer only (not WASM -- server encrypts/decrypts)
@inject ProtectedSessionStorage SessionStorage
@inject ProtectedLocalStorage LocalStorage

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        // Session storage (cleared when tab closes)
        await SessionStorage.SetAsync("cart", cartItems);
        var result = await SessionStorage.GetAsync<List<CartItem>>("cart");
        if (result.Success) { cartItems = result.Value!; }

        // Local storage (persists across sessions)
        await LocalStorage.SetAsync("preferences", userPrefs);
    }
}

For InteractiveWebAssembly, use JS interop to access browser storage directly:

// WASM: Direct browser storage via JS interop
await JSRuntime.InvokeVoidAsync("localStorage.setItem", "key",
    JsonSerializer.Serialize(value, AppJsonContext.Default.UserPrefs));

var json = await JSRuntime.InvokeAsync<string?>("localStorage.getItem", "key");
if (json is not null)
{
    value = JsonSerializer.Deserialize(json, AppJsonContext.Default.UserPrefs);
}

Gotcha: ProtectedBrowserStorage is not available during prerendering. Always access it in OnAfterRenderAsync(firstRender: true), never in OnInitializedAsync.


JavaScript Interop

Calling JavaScript from.NET

@inject IJSRuntime JSRuntime

// Invoke a global JS function
await JSRuntime.InvokeVoidAsync("console.log", "Hello from Blazor");

// Invoke and get a return value
var width = await JSRuntime.InvokeAsync<int>("getWindowWidth");

// With timeout (important for Server to avoid hanging circuits)
var result = await JSRuntime.InvokeAsync<string>(
    "expensiveOperation",
    TimeSpan.FromSeconds(10),
    inputData);

JavaScript Module Imports (AOT-Safe)

// Import a JS module -- trim-safe, no reflection
private IJSObjectReference? module;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        module = await JSRuntime.InvokeAsync<IJSObjectReference>(
            "import", "./js/interop.js");
        await module.InvokeVoidAsync("initialize", elementRef);
    }
}

// Always dispose module references
public async ValueTask DisposeAsync()
{
    if (module is not null)
    {
        await module.DisposeAsync();
    }
}
// wwwroot/js/interop.js
export function initialize(element) {
    // Set up the element
}

export function getValue(element) {
    return element.value;
}

Calling.NET from JavaScript

// Instance method callback
private DotNetObjectReference<MyComponent>? dotNetRef;

protected override void OnInitialized()
{
    dotNetRef = DotNetObjectReference.Create(this);
}

[JSInvokable]
public void OnJsEvent(string data)
{
    message = data;
    StateHasChanged();
}

public void Dispose()
{
    dotNetRef?.Dispose();
}
// Call .NET from JS
export function registerCallback(dotNetRef) {
    document.addEventListener('custom-event', (e) => {
        dotNetRef.invokeMethodAsync('OnJsEvent', e.detail);
    });
}

JS Interop per Render Mode

ConcernInteractiveServerInteractiveWebAssemblyInteractiveAutoHybrid
JS call timingAfter SignalR confirms renderAfter WASM runtime loadsSignalR initially, then direct after WASM switchAfter WebView loads
OnAfterRender availableYesYesYesYes
IJSRuntime sync callsNot supported (async only)IJSInProcessRuntime availableAsync-only during Server phase; IJSInProcessRuntime after WASM switchIJSInProcessRuntime available
Module importsVia SignalR (latency)Direct (fast)SignalR (Server phase), direct (WASM phase)Direct (fast)

Gotcha: In InteractiveServer, all JS interop calls travel over SignalR, adding network latency. Minimize round trips by batching operations into a single JS function call.


EditForm Validation

Basic EditForm with Data Annotations

<EditForm Model="product" OnValidSubmit="HandleSubmit" FormName="product-form">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div>
        <label for="name">Name:</label>
        <InputText id="name" @bind-Value="product.Name" />
        <ValidationMessage For="() => product.Name" />
    </div>

    <div>
        <label for="price">Price:</label>
        <InputNumber id="price" @bind-Value="product.Price" />
        <ValidationMessage For="() => product.Price" />
    </div>

    <div>
        <label for="category">Category:</label>
        <InputSelect id="category" @bind-Value="product.Category">
            <option value="">Select...</option>
            <option value="Electronics">Electronics</option>
            <option value="Clothing">Clothing</option>
        </InputSelect>
        <ValidationMessage For="() => product.Category" />
    </div>

    <button type="submit">Save</button>
</EditForm>

@code {
    private ProductModel product = new();

    private async Task HandleSubmit()
    {
        await ProductService.CreateAsync(product);
        Navigation.NavigateTo("/products");
    }
}

Model with Validation Attributes

public sealed class ProductModel
{
    [Required(ErrorMessage = "Product name is required")]
    [StringLength(200, MinimumLength = 1)]
    public string Name { get; set; } = "";

    [Range(0.01, 1_000_000, ErrorMessage = "Price must be between {1} and {2}")]
    public decimal Price { get; set; }

    [Required(ErrorMessage = "Category is required")]
    public string Category { get; set; } = "";
}

EditForm with Enhanced Form Handling (.NET 8+)

Static SSR forms require FormName and use [SupplyParameterFromForm]:

@page "/products/create"

<EditForm Model="product" OnValidSubmit="HandleSubmit" FormName="create-product" Enhance>
    <DataAnnotationsValidator />
    <!-- form fields -->
    <button type="submit">Create</button>
</EditForm>

@code {
    [SupplyParameterFromForm]
    private ProductModel product { get; set; } = new();

    private async Task HandleSubmit()
    {
        await ProductService.CreateAsync(product);
        Navigation.NavigateTo("/products");
    }
}

The Enhance attribute enables enhanced form handling -- the form submits via fetch and patches the DOM without a full page reload.

Gotcha: FormName must be unique across all forms on the page. Duplicate FormName values cause ambiguous form submission errors.


QuickGrid

QuickGrid is a high-performance grid component built into Blazor (.NET 8+). It supports sorting, filtering, pagination, and virtualization.

Basic QuickGrid

@using Microsoft.AspNetCore.Components.QuickGrid

<QuickGrid Items="products">
    <PropertyColumn Property="p => p.Name" Sortable="true" />
    <PropertyColumn Property="p => p.Price" Format="C2" Sortable="true" />
    <PropertyColumn Property="p => p.Category" Sortable="true" />
    <TemplateColumn Title="Actions">
        <button @onclick="() => Edit(context)">Edit</button>
    </TemplateColumn>
</QuickGrid>

@code {
    private IQueryable<Product> products = Enumerable.Empty<Product>().AsQueryable();

    protected override async Task OnInitializedAsync()
    {
        var list = await ProductService.GetAllAsync();
        products = list.AsQueryable();
    }

    private void Edit(Product product) => Navigation.NavigateTo($"/products/{product.Id}/edit");
}

QuickGrid with Pagination

<QuickGrid Items="products" Pagination="pagination">
    <PropertyColumn Property="p => p.Name" Sortable="true" />
    <PropertyColumn Property="p => p.Price" Format="C2" />
</QuickGrid>

<Paginator State="pagination" />

@code {
    private PaginationState pagination = new() { ItemsPerPage = 20 };
    private IQueryable<Product> products = default!;
}

QuickGrid with Virtualization

For large datasets, virtualization renders only visible rows:

<QuickGrid Items="products" Virtualize="true" ItemSize="50">
    <PropertyColumn Property="p => p.Name" />
    <PropertyColumn Property="p => p.Price" Format="C2" />
</QuickGrid>

QuickGrid OnRowClick (.NET 11 Preview)

.NET 11 adds OnRowClick to QuickGrid for row-level click handling without template columns:

<QuickGrid Items="products" OnRowClick="HandleRowClick">
    <PropertyColumn Property="p => p.Name" />
    <PropertyColumn Property="p => p.Price" Format="C2" />
</QuickGrid>

@code {
    private void HandleRowClick(GridRowClickEventArgs<Product> args)
    {
        Navigation.NavigateTo($"/products/{args.Item.Id}");
    }
}

Fallback (net10.0): Use a TemplateColumn with a click handler or wrap each row in a clickable element.

Source: ASP.NET Core.NET 11 Preview - QuickGrid enhancements


.NET 11 Preview Features

EnvironmentBoundary Component

EnvironmentBoundary conditionally renders content based on the hosting environment (Development, Staging, Production):

<EnvironmentBoundary Include="Development">
    <p>Debug panel -- only visible in Development</p>
    <DebugToolbar />
</EnvironmentBoundary>

<EnvironmentBoundary Exclude="Production">
    <p>Testing controls -- hidden in Production</p>
</EnvironmentBoundary>

Fallback (net10.0): Inject IWebHostEnvironment and use conditional rendering in @code.

Source: ASP.NET Core.NET 11 Preview - EnvironmentBoundary

Label and DisplayName Support

.NET 11 adds [DisplayName] support for input components, automatically generating <label> elements:

<EditForm Model="model" FormName="contact">
    <!-- Automatically renders <label> from [DisplayName] -->
    <InputText @bind-Value="model.FullName" />
    <InputText @bind-Value="model.EmailAddress" />
</EditForm>

@code {
    private ContactModel model = new();
}

// Model
public sealed class ContactModel
{
    [DisplayName("Full Name")]
    [Required]
    public string FullName { get; set; } = "";

    [DisplayName("Email Address")]
    [EmailAddress]
    public string EmailAddress { get; set; } = "";
}

Fallback (net10.0): Add explicit <label for="..."> elements manually.

Source: ASP.NET Core.NET 11 Preview - Label/DisplayName

IHostedService in WebAssembly

.NET 11 allows IHostedService implementations to run in Blazor WebAssembly, enabling background tasks in the browser:

// Register in WASM Program.cs
builder.Services.AddHostedService<DataSyncService>();

public sealed class DataSyncService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await SyncDataFromServer();
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
}

Fallback (net10.0): Use a Timer in a component or inject a singleton service that starts background work on first use.

Source: ASP.NET Core.NET 11 Preview - IHostedService in WASM

SignalR ConfigureConnection

.NET 11 adds ConfigureConnection to the Blazor Server circuit hub, allowing customization of the SignalR connection (e.g., adding custom headers, configuring reconnection):

// Program.cs
app.MapBlazorHub(options =>
{
    options.ConfigureConnection = connection =>
    {
        connection.Metadata["tenant"] = "default";
    };
});

Fallback (net10.0): Use IHubFilter or middleware to inspect/modify connections at the hub level.

Source: ASP.NET Core.NET 11 Preview - SignalR ConfigureConnection


Agent Gotchas

  1. Do not call JS interop in OnInitializedAsync. The DOM is not available yet. Use OnAfterRenderAsync(firstRender: true) for JS calls that need DOM elements.
  2. Do not forget StateHasChanged() after external state changes. When state changes from a non-Blazor context (timer, event handler, JS callback), call StateHasChanged() or InvokeAsync(StateHasChanged) to trigger re-render.
  3. Do not use ProtectedBrowserStorage during prerendering. It throws because no interactive circuit exists yet. Access it only in OnAfterRenderAsync.
  4. Do not forget FormName on Static SSR forms. Without it, form submissions in Static SSR mode are not routed to the correct handler.
  5. Do not dispose DotNetObjectReference before JS is done with it. Premature disposal causes JSException when JavaScript tries to invoke the callback. Dispose in Dispose() or DisposeAsync().
  6. Do not assume Scoped services are per-request in Blazor Server. Scoped services live for the entire circuit. Use OwningComponentBase<T> when you need component-scoped service lifetimes.

Prerequisites

  • .NET 8.0+ (QuickGrid, enhanced form handling, cascading values with IsFixed)
  • Microsoft.AspNetCore.Components.QuickGrid package for QuickGrid
  • .NET 11 preview for EnvironmentBoundary, Label/DisplayName, QuickGrid OnRowClick, IHostedService in WASM

Knowledge Sources

Blazor component patterns in this skill are grounded in guidance from:

  • Damian Edwards -- Razor and Blazor component design patterns, render mode architecture, and performance best practices. Principal architect on the ASP.NET team.
These sources inform the patterns and rationale presented above. This skill does not claim to represent or speak for any individual.

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

32.05%
按下载量换算47

Claude

30.98%
按下载量换算46

Cursor

19.31%
按下载量换算29

Gemini CLI

8.47%
按下载量换算13

安全审计

Gen Agent Trust Hub

通过

Socket

未通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills