Skip to main content

Show HTML in a read-only rich text editor in ASP.NET Core

The editor showing a formatted document

Sometimes people should see content, with its formatting, but not change it: a submitted form, a contract waiting for approval, or a viewer without edit rights. One attribute does it.

The attribute

<richtextbox name="Contract"
             read-only="true"
             toolbar="full"
             height="400px"
             html="@Model.ContractHtml"></richtextbox>

People can read and select text, but not change it. Formatting and styles are kept.

Decide it from the user

read-only takes a value, so your own logic can decide it:

<richtextbox asp-for="Body"
             read-only="@(!User.IsInRole("Editor"))"
             toolbar="default"></richtextbox>

Read-only is not security

This setting lives in the browser, and it stops honest mistakes. Someone who wants to can still send your form a changed value by hand. If a person may not edit, your handler has to refuse the save:

public IActionResult OnPost()
{
    if (!User.IsInRole("Editor")) return Forbid();
    // save
    return RedirectToPage();
}

Do you need an editor at all?

An editor is much more script than a plain page. If people only read the content and never switch to editing, print the cleaned HTML instead, which is lighter and easier for search engines:

<div class="article">@Html.Raw(Model.CleanHtml)</div>

This is safe only if the HTML was cleaned on the server. A read-only editor is the better choice when the same page switches between reading and editing, or when people should use tools such as comments on content they cannot change.

Read next