Skip to main content

Use several rich text editors on one ASP.NET Core page

The editor with a formatted document

Forms often need more than one rich text field: a summary and a body, or a question and an answer. RichTextBox editors on the same page are independent, each with its own toolbar and content.

Two editors, two properties

public class ArticleModel : PageModel
{
    [BindProperty, RichTextHtml(MaxTextLength = 300)]
    public string? Summary { get; set; }

    [BindProperty, RichTextHtml]
    public string? Body { get; set; }
}
<form method="post">
    <richtextbox asp-for="Summary" toolbar="basic" height="200px"></richtextbox>
    <richtextbox asp-for="Body" toolbar="default" height="450px"></richtextbox>
    <button type="submit">Save</button>
</form>

Each posts to its own property, and each has its own limit and cleaning.

Without a model

Give each a different name. Two editors with the same name would post over each other:

<richtextbox id="editor1" name="editor1" toolbar="default" height="250px"></richtextbox>
<richtextbox id="editor2" name="editor2" toolbar="basic" height="200px"></richtextbox>

Reach each one from JavaScript

var body = window.richTextBoxEditors.editor1;
var html = body.getHTMLCode();
window.richTextBoxEditors.editor2.setHTMLCode("<p>Copied: " + html.length + " characters</p>");

Keep their drafts apart

If you use autosave, give each a different auto-save-key. Otherwise one's draft could appear in the other.

Many editors on one page

The script files load only once, however many editors a page has, but each editor still takes memory and time to start. For a long list where each row could be edited, a page with dozens of editors gets slow. Start with plain text, and create the editor when someone clicks to edit that row.

Read next