Developing a New Module with EasyAdminBlazor.Cms

EasyAdminBlazor.Cms is a frontend rapid-development extension for developers. Developers write pages in Razor and declare content structures with [CmsPage] / [CmsDataType] to automatically generate backend content management. Content editors can manage data, categories, page elements, SEO, and comment moderation without changing code.

Goal: write a Razor page, add an attribute, retrieve data through a public method, and mark page elements with <vc:textblock>. It then runs. The extension automatically generates backend menus, database tables, fields, categories, SEO, and Live Edit.

1. Install and Register the CMS Extension

First, reference the CMS extension package:

<PackageReference Include="EasyAdminBlazor.Cms" Version="2.5.0" />

Register it in the EasyAdminBlazor extension chain in Program.cs:

builder.AddEasyAdminBlazor(new EasyAdminBlazorOptions { ... })
    // ...your existing extension chain...
    .AddEasyAdminBlazorCms(o => o.EnableComments = true);

AddEasyAdminBlazorCms() registers the CMS data services, page collector, element cache, SEO filter, and startup initializer. At startup, it automatically synchronizes the CMS table schema, scans for [CmsPage] / [CmsDataType], generates backend menus, and synchronizes custom fields. You do not need to write entities, migrations, or backend management pages manually.

Comments are optional and EnableComments defaults to false. Only when enabled does the CMS create the cms_comment table, add the "Comment Review" menu under CMS, and accept front-end submissions through ICmsCommentService.AddAsync. When disabled, the menu is hidden automatically (existing menu rows are kept and reappear once you switch it back on) and the comment table and data are left untouched.

Next, add the Live Edit script at the end of the <body> in the host project's root component (usually Components/App.razor), after blazor.web.js:

<script src="@Assets["_content/EasyAdminBlazor.Cms/cms-inline-edit.js"]"></script>

This script provides window.cmsInlineEdit, which is required by Live Edit in the backend Elements tab. If the host project does not include it, the page preview will still open, but you will not be able to click content to edit and save it.

2. Define Content-Type Constants

Add an entry to the content-type constants file in the host project. The page attribute and service calls will share this constant.

public static class CmsContentTypes
{
    public const string Case = "case";
}

3. Create the Page and PageModel

Add [CmsPage] to the PageModel. This is the only configuration that must be written manually for the module.

[CmsPage(
    PageName = "Customer Cases",                 // Backend menu name
    Kind = CmsPageKind.DataListWithCategory,     // Page type; determines backend tabs
    ContentType = CmsContentTypes.Case,
    Sort = 55,                                    // Backend menu order
    HasSeo = true,                                // Whether content-level SEO fields are shown
    Fields = new[]                                // Custom fields
    {
        $"client:Client Name:{CmsFieldTypes.Text}",
        $"industry:Industry:{CmsFieldTypes.Text}",
        $"result:Project Results:{CmsFieldTypes.Textarea}"
    },
    HiddenFields = new[]                          // Built-in fields hidden from the backend
    {
        CmsFieldNames.Slug,
        CmsFieldNames.Summary
    })]
public class CasesModel : PageModel
{
    private readonly ICmsContentService _cms;

    public CasesModel(ICmsContentService cms) => _cms = cms;

    public CmsItemPage Items { get; set; } = new();
    public CmsCategoryView Category { get; set; }
    public List<CmsCategoryView> Categories { get; set; } = new();

    public async Task OnGet(string category, int pageIndex = 1)
    {
        Categories = await _cms.GetCategoriesAsync(CmsContentTypes.Case);
        Category = Categories.FirstOrDefault(x => x.Slug == category);

        Items = await _cms.GetItemsPageAsync(
            CmsContentTypes.Case,
            Category?.Id,
            pageIndex: pageIndex,
            pageSize: 12,
            onlyAudit: true);
    }
}

List and Detail Pages

A module usually consists of a list page and a detail page. Content data is managed on the list page; the detail page only displays the same content item and manages its own page elements. Link list items to the detail page using Slug. Do not treat the detail page as a second data-management entry point.

[CmsPage(
    PageName = "News",
    Kind = CmsPageKind.DataListWithCategory,
    Route = "/News",
    ContentType = CmsContentTypes.News,
    HasSeo = true,
    Fields = new[]
    {
        $"commentable:Allow Comments:{CmsFieldTypes.Bool}"
    })]
public class NewsModel(ICmsContentService cms) : PageModel
{
    public List<CmsItemView> Items { get; set; } = [];
    public CmsItemPage Data { get; set; } = new();

    public async Task OnGet(long? categoryId, int pageIndex = 1)
    {
        Data = await cms.GetItemsPageAsync(
            CmsContentTypes.News,
            categoryId,
            pageIndex,
            pageSize: 10,
            onlyAudit: true);

        Items = Data.Items;
    }
}

// Add [CmsPage] to a detail page only if its page elements need to be editable.
// If it only displays content and has no editable elements, the attribute is not needed.
[CmsPage(
    PageName = "News Details",
    Kind = CmsPageKind.DataDetail,
    Route = "/News/{slug}",
    ContentType = CmsContentTypes.News)]
public class NewsDetailModel(ICmsContentService cms) : PageModel
{
    public CmsItemView? Article { get; set; }

    public async Task<IActionResult> OnGet(string slug)
    {
        Article = await cms.GetItemAsync(CmsContentTypes.News, slug);
        return Article == null ? NotFound() : Page();
    }
}

On the list page, output a detail link using Slug:

@foreach (var item in Model.Items) {
<a asp-page="/NewsDetail" asp-route-slug="@item.Slug">@item.Title</a>
}

The detail page only reads the current content item. Use <vc:textblock> only for static content; do not wrap dynamic titles or body content in it:

<vc:textblock code="news-banner">
    <h1>News Details</h1>
</vc:textblock>

<div>@Html.Raw(Model.Article?.Content)</div>

The content type for detail-page elements is determined automatically by the page Key (for example, news-slug). You do not need to specify content-type manually, and detail-page elements will not be mixed with elements of the list page's news content type.

In the backend, a detail-page menu is generated only when [CmsPage] is declared and Kind = CmsPageKind.DataDetail. It contains only the Elements tab; Data, Categories, and SEO are not shown. Detail-page elements are stored separately under the page's Key. The body, category, audit status, and SEO are managed on the list page.

The backend preview automatically selects a record with a slug from content that has been approved and enabled, then opens /News/{slug} for element editing. If there is no previewable content, or the route does not contain exactly one {slug} parameter, a prompt is displayed asking you to open a specific detail page from the list.

Detail-page SEO uses seoTitle, seoKeyword, and seoDescription from the list data; SEO is not configured separately on the detail page. If the detail page has no editable elements, do not add [CmsPage].

Custom Field Format

The format is key:Label:Type[:Option1|Option2]. Use constants from CmsFieldTypes for the type:

$"department:Hiring Department:{CmsFieldTypes.Text}",
$"headcount:Number of Positions:{CmsFieldTypes.Number}",
$"requirements:Requirements:{CmsFieldTypes.Textarea}",
$"status:Status:{CmsFieldTypes.Select}:Enabled|Disabled",
$"recommend:Recommended:{CmsFieldTypes.Bool}"

Available types: text, textarea, number, select, image, and bool.

If a definition is invalid, startup fails immediately and reports the page name, field definition, and available types. The select type must include options.

4. Retrieve Data on the Frontend

Use ICmsContentService for lists, pagination, details, categories, previous/next items, and related content. Do not query Db.CmsData directly.

var page = await _cms.GetItemsPageAsync(CmsContentTypes.Case, pageIndex: 1);
var item = await _cms.GetItemAsync(CmsContentTypes.Case, slug);
var byId = await _cms.GetItemAsync(CmsContentTypes.Case, 123); // Supports legacy links
var categories = await _cms.GetCategoriesAsync(CmsContentTypes.Case);
var (prev, next) = await _cms.GetNeighborsAsync(CmsContentTypes.Case, item.CategoryId, item.PublishTime.Value, item.Id);
var related = await _cms.GetRelatedAsync(CmsContentTypes.Case, item.Get("keywords"), item.Id);

Comments are stored in the separate cms_comment table, not in cms_data. Use ICmsCommentService (see Pages/NewsDetail.cshtml.cs and Pages/News.cshtml.cs in the Demo):

// NewsDetail: retrieve approved, non-spam comments
var comments = await _comments.GetApprovedAsync(CmsContentTypes.News, item.Id, take: 20);

// NewsDetail: submit a comment; AddAsync marks it as pending moderation
await _comments.AddAsync(new CmsComment
{
    ContentType = CmsContentTypes.News,
    ContentId = item.Id,
    AuthorName = input.Name,
    Content = input.Text
});

// News: batch-count approved comments for list items
var counts = await _comments.CountApprovedByContentIdsAsync(
    CmsContentTypes.News,
    items.Select(x => x.Id));

GetApprovedAsync returns only approved, non-spam comments and is suitable for direct display on a detail page. Comments submitted through AddAsync are pending moderation by default and are displayed only after approval. CountApprovedByContentIdsAsync is suitable for batch-counting comment totals on list pages. The submission form should also enforce business rules based on the commentable flag and CAPTCHA. The Demo's NewsDetail shows this usage. Do not read or write CmsComment or cms_data directly from a page.

Filter at the database level using custom fields:

// Exact match on a single field
var articles = await _cms.GetItemsByFieldAsync(
    CmsContentTypes.News, "recommend", "true", take: 3, onlyAudit: true);

// Combine multiple fields with AND; contains: true means a partial match
var list = await _cms.GetItemsByFieldsAsync(CmsContentTypes.News, new[]
{
    new CmsFieldFilter("recommend", "true"),
    new CmsFieldFilter("source", "Glitter", contains: true)
});

Read custom fields:

@item.Get("client") @item.GetBool("recommend") @item.GetInt("viewHits") @item.GetDecimal("price")

5. Page Elements

First, register the tag helper in Pages/_ViewImports.cshtml:

@addTagHelper *, EasyAdminBlazor.Cms

Then mark editable elements with <vc:textblock>. Divide content by visual section; do not split the heading, subtitle, and description into separate codes. Live Edit supports editing the entire HTML block:

<vc:textblock code="CASE_PAGE_HERO">
    <p>CASES</p>
    <h1>Customer Cases</h1>
    <p>See how we help customers deliver successful projects.</p>
</vc:textblock>

Elements are unique by (ContentType, Code). Use a module prefix to avoid naming collisions across modules. In the backend, you can click a block in Live Edit under the Elements tab to edit the entire block directly on the page.

6. Localization

The CMS admin UI (data, categories, elements, comment moderation, and SEO) ships with Chinese and English text. The language packs live in the EasyAdminBlazor.Common block of Extensions/EasyAdminBlazor.Cms/Locales/zh.json and en.json. They are merged into CommonLocalizer automatically when the extension is registered; no extra configuration is required.

To add a language, copy zh.json to {culture}.json and translate it. The csproj embeds Locales/*.json with a wildcard, so no code change is needed. The PageName and Fields text on your own pages belongs to the host project; translate it through the host's language pack (EasyAdminBlazor.Common or an entity block).

7. Run the Application

After the website starts, the extension automatically:

  • Synchronizes the schemas for cms_data, cms_category, cms_field, cms_element, and cms_page_seo.
  • Synchronizes field definitions based on Fields; invalid definitions cause startup to fail.
  • Generates backend menus for pages declared with [CmsPage]; pages with business data also get create, edit, and delete buttons.
  • Generates tabs for list pages according to Kind: Data → Categories → Elements → SEO, with SEO always last.
  • Generates only the Elements tab for DataDetail pages. Do not add [CmsPage] to detail pages that have no editable elements.
  • Uses HasSeo to determine whether content-level SEO inputs are shown for list content. Detail-page SEO uses the SEO fields on the list data.

Things You Do Not Need to Do

  • You do not need to write entity classes, a DbContext, or migration scripts.
  • You do not need to write backend management pages.
  • You do not need to write a View class for every module.
  • You do not need to add records manually to the menu table.

Cases Requiring Additional Handling

  • If a page has no frontend entry point, use [CmsDataType] instead of [CmsPage].
  • If a detail page only displays content and has no editable elements, you do not need to add [CmsPage].
  • If you need more complex queries combining custom fields, add methods to ICmsContentService.