RazorHelpers

A powerful library for rendering Razor components as HTML strings or IResult responses in ASP.NET Core minimal APIs. Features fluent HTML builders for tables, selects, and dynamic content.

80+
HTML Elements
.NET 9-10
Support
Fluent
API Design
Type-Safe
Collections

Why Choose RazorHelpers?

Build HTML programmatically with a fluent, type-safe API designed for minimal APIs and server-side rendering.

Fluent HTML Builder

Chain methods to build complex HTML structures with IntelliSense support and compile-time safety.

Collection Builders

Generate tables, selects, and lists from collections with automatic column definitions and grouping.

Minimal API Ready

Return HTML directly from endpoints with Results.Razor() or render components to strings.

Get Started in Minutes

Install RazorHelpers and start building HTML with a fluent, type-safe API.

1. Installation

$ dotnet add package RazorHelpers

2. Register Services

builder.Services.AddRazorHelpers();

Add to Program.cs

3. Start Building

using RazorHelpers;
var html = Html.Div("Hello World");
Program.cs
using RazorHelpers;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorHelpers();

var app = builder.Build();

// Return HTML from minimal API endpoints
app.MapGet("/", () => RazorResults.Razor(
    Html.Div()
        .Class("container")
        .Child(Html.H1("Welcome!"))
        .Child(Html.P("Built with RazorHelpers"))
));

// Generate tables from collections
app.MapGet("/users", () => RazorResults.Razor(
    Html.Table(users)
        .Class("table")
        .Column("Name", u => u.Name)
        .Column("Email", u => u.Email)
));

app.Run();

API Reference

Comprehensive builders for every HTML element and collection type.

Html Static Factory

The Html class provides static methods for creating all HTML elements with a fluent API.

Element Methods

Html.Div() - Container element
Html.Span() - Inline element
Html.H1() - H6() - Headings
Html.P() - Paragraph
Html.A(href, text) - Anchor link
Html.Img(src, alt) - Image
Html.Form(action, method) - Form
Html.Input(type, name) - Input field
// Build a card component
var card = Html.Div()
    .Class("card", "shadow-lg")
    .Id("user-card")
    .Child(Html.Img("/avatar.jpg", "Avatar")
        .Class("rounded-full"))
    .Child(Html.H2("John Doe"))
    .Child(Html.P("Software Engineer")
        .Class("text-gray-500"))
    .Child(Html.A("mailto:john@example.com", "Email")
        .Class("btn", "btn-primary"));

// Conditional classes
var btn = Html.Button("Submit")
    .Class("btn")
    .ClassIf("btn-disabled", isDisabled)
    .Attr("disabled", isDisabled);

// Inline styles
var alert = Html.Div("Success!")
    .Style("color", "green")
    .Style("padding", "1rem");

Fluent Methods

Attributes
  • .Class() - CSS classes
  • .ClassIf() - Conditional class
  • .Id() - Element ID
  • .Attr() - Any attribute
  • .Attrs() - Multiple attributes
  • .Data() - Data attributes
Styling
  • .Style() - Single style
  • .Styles() - Multiple styles
Content
  • .Text() - Encoded text
  • .Raw() - Raw HTML
  • .Child() - Add child
  • .Children() - Multiple children
  • .Content() - RenderFragment

TableBuilder<T>

Generate HTML tables from collections with automatic column definitions, row styling, and custom cell rendering.

Table Methods

.Header() - Define header row
.Column(header, selector) - Define column
.Row(selector) - Custom row rendering
.RowClass(selector) - Conditional row class
.Caption() - Table caption
.Foot() - Custom tfoot element
// Simple table from collection
var table = Html.Table(users)
    .Class("table", "table-striped")
    .Column("Name", u => u.Name)
    .Column("Email", u => u.Email)
    .Column("Status", u => u.IsActive ? "Active" : "Inactive");

// With custom cell rendering
var table = Html.Table(users)
    .Column("Name", u => Html.Strong(u.Name))
    .Column("Email", u =>
        Html.A($"mailto:{u.Email}", u.Email))
    .Column("Status", u =>
        Html.Span(u.IsActive ? "Active" : "Inactive")
            .Class(u.IsActive ? "text-green-500" : "text-red-500"));

// Conditional row styling
var table = Html.Table(orders)
    .Column("Order #", o => o.Id.ToString())
    .Column("Total", o => o.Total.ToString("C"))
    .RowClass(o => o.IsPending ? "bg-yellow-50" : "");

SelectBuilder<T>

Create dropdown selects from collections with support for grouping, placeholders, and conditional selection.

Select Methods

.Value(selector) - Option value
.Text(selector) - Option text
.Placeholder(text) - Empty option
.SelectedValue(value) - Pre-select option
.Selected(predicate) - Conditional selection
.GroupBy(selector) - Create optgroups
.DisabledOption(predicate) - Disable options
// Simple select from collection
var select = Html.Select(countries, "country")
    .Value(c => c.Code)
    .Text(c => c.Name)
    .Placeholder("Select a country...")
    .SelectedValue("us");

// Grouped select (optgroups)
var carSelect = Html.Select(cars, "car")
    .Value(c => c.Id)
    .Text(c => c.Model)
    .GroupBy(c => c.Manufacturer);
// Renders:
// <optgroup label="Toyota">
//   <option value="1">Camry</option>
// </optgroup>

// With disabled options
var planSelect = Html.Select(plans, "plan")
    .Value(p => p.Id)
    .Text(p => p.Name)
    .DisabledOption(p => p.RequiresPremium);

Rendering Options

Multiple ways to render HTML elements as strings or IResult responses.

Rendering Methods

RazorResults.Razor()

Returns IResult for minimal API endpoints.

.RenderAsync()

Renders RenderFragment to HTML string asynchronously.

ComponentHelper

Renders Razor components to strings with parameters.

// Minimal API endpoint
app.MapGet("/page", () =>
    RazorResults.Razor(Html.Div("Hello")));

// With model binding
app.MapGet("/user/{id}", (int id) =>
    RazorResults.Razor(template, new { Id = id }));

// Render to string
var html = await Html.Div("Content")
    .Render()
    .RenderAsync(services);

// Render component with parameters
var html = await ComponentHelper
    .RenderComponentAsync<MyComponent>(
        services,
        new Dictionary<string, object?>
        {
            ["Title"] = "Hello"
        });

Lists and Iteration

Build lists and repeat elements from collections with Html.Ul(), Html.Ol(), and Html.Each().

List Helpers

// Simple list from strings
var ul = Html.Ul(items, x => x);

// List with custom item rendering
var ul = Html.Ul(products, p =>
    Html.A($"/product/{p.Id}", p.Name));

// Ordered list
var ol = Html.Ol(steps, s => s.Title);

Html.Each() Iterator

// Repeat elements for each item
var cards = Html.Each(products, p =>
    Html.Div()
        .Class("card")
        .Child(Html.H3(p.Name))
        .Child(Html.P(p.Description)));

// With index
var rows = Html.Each(items, (item, i) =>
    Html.Div($"{i + 1}. {item.Name}"));

Text Formatting Elements

All common HTML text formatting elements are available with the fluent API.

Emphasis

  • Html.Strong()
  • Html.Em()
  • Html.B()
  • Html.I()
  • Html.U()
  • Html.S()

Annotations

  • Html.Mark()
  • Html.Del()
  • Html.Ins()
  • Html.Sub()
  • Html.Sup()
  • Html.Small()

Code & Quotes

  • Html.Code()
  • Html.Pre()
  • Html.Kbd()
  • Html.Samp()
  • Html.Var()
  • Html.Blockquote()
  • Html.Q()
  • Html.Cite()

Other

  • Html.Abbr()
  • Html.Time()
  • Html.Address()
  • Html.Br()
  • Html.Hr()
  • Html.Wbr()

Ready to Get Started?

Install RazorHelpers and start building HTML with a fluent, type-safe API today.

$ dotnet add package RazorHelpers