Dotnet blazor

From managedcode/PrompterOne · View interactive version

Dotnet blazor is an AI agent skill from the GitHub repository managedcode/PrompterOne. Build and review Blazor applications across server, WebAssembly, web app, and hybrid scenarios with correct component design, state flow, rendering, and hosting choices.

How to use this skill

Skill file

Blazor

Trigger On

Documentation

References

Render Modes (.NET 8+)

| Mode | Where It Runs | Best For |

|------|---------------|----------|

| Static | Server (no interactivity) | SEO pages, marketing content |

| InteractiveServer | Server via SignalR | Real-time apps, thin clients |

| InteractiveWebAssembly | Browser via WASM | Offline-capable, client-heavy |

| InteractiveAuto | Server first, then WASM | Best of both worlds |

Applying Render Modes

@* Per-component *@
@rendermode InteractiveServer

@* Or in App.razor for global *@
<Routes @rendermode="InteractiveAuto" />

InteractiveAuto Architecture

First Request:
  Browser → Server (Interactive Server) → Fast response

Subsequent Requests:
  Browser → WASM (downloaded in background) → No server needed

Workflow

  1. Choose render mode based on requirements:
  1. Design components for reusability:
  1. Handle state correctly:
  1. Validate in both environments (for Auto mode)

Component Patterns

Basic Component

@* Counter.razor *@
<button @onclick="IncrementCount">
    Clicked @count times
</button>

@code {
    private int count = 0;

    [Parameter]
    public int InitialCount { get; set; } = 0;

    protected override void OnInitialized()
    {
        count = InitialCount;
    }

    private void IncrementCount() => count++;
}

Parameter and Event Callbacks

@* Parent.razor *@
<ChildComponent Value="@value" ValueChanged="@OnValueChanged" />

@* ChildComponent.razor *@
@code {
    [Parameter] public string Value { get; set; } = "";
    [Parameter] public EventCallback<string> ValueChanged { get; set; }

    private async Task UpdateValue(string newValue)
    {
        await ValueChanged.InvokeAsync(newValue);
    }
}

State Persistence (.NET 8+)

@* Prevents double-fetch during prerender + hydration *@
@code {
    [PersistentState]
    public List<Product> Products { get; set; } = [];

    protected override async Task OnInitializedAsync()
    {
        // Only fetches once, persisted across prerender
        Products ??= await Http.GetFromJsonAsync<List<Product>>("api/products");
    }
}

Data Access Pattern for Auto Mode

// Shared interface
public interface IProductService
{
    Task<List<Product>> GetProductsAsync();
}

// Server implementation (direct DB access)
public class ServerProductService : IProductService
{
    private readonly AppDbContext _db;
    public async Task<List<Product>> GetProductsAsync()
        => await _db.Products.ToListAsync();
}

// Client implementation (HTTP call)
public class ClientProductService : IProductService
{
    private readonly HttpClient _http;
    public async Task<List<Product>> GetProductsAsync()
        => await _http.GetFromJsonAsync<List<Product>>("api/products");
}

// Registration
// Server: builder.Services.AddScoped<IProductService, ServerProductService>();
// Client: builder.Services.AddScoped<IProductService, ClientProductService>();

Anti-Patterns to Avoid

| Anti-Pattern | Why It's Bad | Better Approach |

|--------------|--------------|-----------------|

| Large components | Hard to maintain, slow renders | Split into smaller components |

| Direct DB access in WASM | No DB in browser | Use HTTP API |

| Ignoring ShouldRender | Unnecessary re-renders | Override when needed |

| Sync JS interop in Server | Blocks SignalR circuit | Use IJSRuntime async |

| No error boundaries | One error crashes app | Use <ErrorBoundary> |

| Forgetting prerender state | Double API calls | Use [PersistentState] |

Performance Best Practices

  1. Virtualize large lists:

```razor

<Virtualize Items="@products" Context="product">

<ProductCard Product="@product" />

</Virtualize>

```

  1. Use @key for list diffing:

```razor

@foreach (var item in items)

{

<ItemComponent @key="item.Id" Item="@item" />

}

```

  1. Debounce rapid events:

```csharp

private Timer? _debounceTimer;

private void OnInput(ChangeEventArgs e)

{

_debounceTimer?.Dispose();

_debounceTimer = new Timer(_ => InvokeAsync(DoSearch), null, 300, Timeout.Infinite);

}

```

  1. Lazy load assemblies (WASM):

```csharp

var assemblies = await LazyAssemblyLoader

.LoadAssembliesAsync(["MyHeavyFeature.wasm"]);

```

JS Interop

Calling JavaScript from C#

@inject IJSRuntime JS

await JS.InvokeVoidAsync("alert", "Hello from Blazor!");
var result = await JS.InvokeAsync<string>("prompt", "Enter name:");

Calling C# from JavaScript

[JSInvokable]
public static string GetMessage() => "Hello from C#!";
DotNet.invokeMethodAsync('MyAssembly', 'GetMessage')
    .then(result => console.log(result));

Deliver

Validate

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.