Example of Events in ASP.NET MVC Rich Text Editor Control
This sample demonstrates the events that trigger on every action of the Rich Text Editor. The event details are showcased in the event trace panel.
Event Trace
@Html.UiRichTextEditor(new UiRichTextEditorOptions
{
Id = "eventsEditor",
ToolbarSettings = new UiRichTextToolbar { Items = (List<string>)ViewData["Tools"] },
QuickToolbarSettings = new UiRichTextQuickToolbar { Text = (List<string>)ViewData["Text"] },
InsertImageSettings = new UiRichTextImageSettings { SaveUrl = Url.Action("SaveImage") },
OnCreated = "created",
OnActionBegin = "actionBegin",
OnActionComplete = "actionComplete",
OnFocus = "focused",
OnBlur = "blurred",
OnChange = "changed",
OnToolbarClick = "toolbarClick",
OnBeforeDialogOpen = "beforeDialogOpen",
OnDialogOpen = "dialogOpen",
OnDialogClose = "dialogClose",
OnBeforeQuickToolbarOpen = "beforeQuickToolbarOpen",
OnQuickToolbarOpen = "quickToolbarOpen",
OnQuickToolbarClose = "quickToolbarClose",
OnImageSelected = "imageSelected",
OnImageUploading = "imageUploading",
OnImageUploadSuccess = "imageUploadSuccess",
OnImageUploadFailed = "imageUploadFailed",
OnImageRemoving = "imageRemoving",
OnResizing = "resizing",
OnResizeStart = "resizeStart",
OnResizeStop = "resizeStop",
OnSelectionChanged = "selectionChanged",
Value = (string)ViewData["RTEValue"]
})
@Html.UiRichTextEditor(new UiRichTextEditorOptions
{
Id = "eventsEditor",
ToolbarSettings = new UiRichTextToolbar { Items = (List<string>)ViewData["Tools"] },
QuickToolbarSettings = new UiRichTextQuickToolbar { Text = (List<string>)ViewData["Text"] },
InsertImageSettings = new UiRichTextImageSettings { SaveUrl = Url.Action("SaveImage") },
OnCreated = "created",
OnActionBegin = "actionBegin",
OnActionComplete = "actionComplete",
OnFocus = "focused",
OnBlur = "blurred",
OnChange = "changed",
OnToolbarClick = "toolbarClick",
OnBeforeDialogOpen = "beforeDialogOpen",
OnDialogOpen = "dialogOpen",
OnDialogClose = "dialogClose",
OnBeforeQuickToolbarOpen = "beforeQuickToolbarOpen",
OnQuickToolbarOpen = "quickToolbarOpen",
OnQuickToolbarClose = "quickToolbarClose",
OnImageSelected = "imageSelected",
OnImageUploading = "imageUploading",
OnImageUploadSuccess = "imageUploadSuccess",
OnImageUploadFailed = "imageUploadFailed",
OnImageRemoving = "imageRemoving",
OnResizing = "resizing",
OnResizeStart = "resizeStart",
OnResizeStop = "resizeStop",
OnSelectionChanged = "selectionChanged",
Value = (string)ViewData["RTEValue"]
})
<div class="demo-property-panel">
<h3>Event Trace</h3>
<div style="height: 200px; overflow: auto" aria-live="polite" aria-label="Event trace"><span id="EventLog"></span></div>
<button type="button" id="clear" class="btn btn-outline-secondary btn-sm mt-2">Clear</button>
</div>
<script>
// Each event writes a line at the top of the trace: "Rich Text Editor <b>name</b> event called".
function appendElement(name, what) {
var line = document.createElement('div');
line.appendChild(document.createTextNode('Rich Text Editor '));
var bold = document.createElement('b');
bold.textContent = name;
line.appendChild(bold);
line.appendChild(document.createTextNode(what || ' event called'));
var log = document.getElementById('EventLog');
log.insertBefore(line, log.firstChild);
}
function created() { appendElement('create'); }
function actionBegin(args) { appendElement(args.requestType, ' action is called'); }
function actionComplete(args) { appendElement(args.requestType, ' action is completed'); }
function focused() { appendElement('focus'); }
function blurred() { appendElement('blur'); }
function changed() { appendElement('change'); }
function toolbarClick() { appendElement('toolbar click'); }
function beforeDialogOpen() { appendElement('beforeDialogOpen'); }
function dialogOpen() { appendElement('dialogOpen'); }
function dialogClose() { appendElement('dialogClose'); }
function beforeQuickToolbarOpen() { appendElement('beforeQuickToolbarOpen'); }
function quickToolbarOpen() { appendElement('quickToolbarOpen'); }
function quickToolbarClose() { appendElement('quickToolbarClose'); }
function imageSelected() { appendElement('imageSelected'); }
function imageUploading() { appendElement('imageUploading'); }
function imageUploadSuccess() { appendElement('imageUploadSuccess'); }
function imageUploadFailed() { appendElement('imageUploadFailed'); }
function imageRemoving() { appendElement('imageRemoving'); }
function resizing() { appendElement('resizing'); }
function resizeStart() { appendElement('resizeStart'); }
function resizeStop() { appendElement('resizeStop'); }
function selectionChanged() { appendElement('selectionChanged'); }
document.getElementById('clear').addEventListener('click', function () { document.getElementById('EventLog').textContent = ''; });
</script>
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class RichTextEditorController : Controller
{
// The page is Views/RichTextEditor/Events.cshtml; it draws what ViewData holds.
public ActionResult Events()
{
ViewData["Tools"] = new List<string>
{
"Bold", "Italic", "Underline", "StrikeThrough", "SuperScript", "SubScript", "|", "FontName", "FontSize", "FontColor", "BackgroundColor", "|", "LowerCase", "UpperCase",
"Formats", "Alignments", "Blockquote", "|", "NumberFormatList", "BulletFormatList", "|", "Outdent", "Indent", "|", "CreateLink", "Image", "Video", "Audio", "CreateTable", "|",
"FormatPainter", "ClearFormat", "|", "EmojiPicker", "Print", "|", "SourceCode", "FullScreen", "|", "Undo", "Redo"
};
ViewData["Text"] = new List<string> { "Bold", "Italic", "Underline" };
ViewData["RTEValue"] = "<p>The Rich Text Editor component is a WYSIWYG ('what you see is what you get') editor that provides the best user experience to create and update the content. Users can format their content using standard toolbar commands.</p>" +
"<p><b> Key features:</b></p><ul><li><p> Provides < IFRAME > and < DIV > modes </p></li><li><p> Capable of handling markdown editing.</p></li>" +
"<li><p> Contains a modular library to load the necessary functionality on demand.</p></li><li><p> Provides a fully customizable toolbar.</p></li>" +
"<li><p> Provides HTML view to edit the source directly for developers.</p></li><li><p> Supports third - party library integration.</p></li>" +
"<li><p> Allows a preview of modified content before saving it.</p></li><li><p> Handles images, hyperlinks, video, hyperlinks, uploads, etc.</p></li>" +
"<li><p> Contains undo / redo manager.</p></li><li><p> Creates bulleted and numbered lists.</p></li></ul>";
return View();
}
/// <summary>The Image sample's uploads: kept in memory (the 50 newest), as a demo needs no storage of its own.</summary>
private static readonly ConcurrentDictionary<string, KeyValuePair<DateTime, byte[]>> Images = new ConcurrentDictionary<string, KeyValuePair<DateTime, byte[]>>();
private const int MaxImageBytes = 2000000;
/// <summary>
/// The Image sample's upload action (InsertImageSettings.SaveUrl): a PNG, JPEG, GIF or WebP file of up to 2 MB, known by its first
/// bytes (not its name), answered with { url }. Anything else is refused with 400. The file comes as UploadFiles (the editor's field,
/// as Syncfusion's) or file.
/// </summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult SaveImage(HttpPostedFileBase file, HttpPostedFileBase uploadFiles)
{
file = file ?? uploadFiles;
if (file == null || file.ContentLength <= 0 || file.ContentLength > MaxImageBytes)
{
return new HttpStatusCodeResult(400, "An image of up to 2 MB is needed.");
}
var bytes = new byte[file.ContentLength];
int read = 0;
while (read < bytes.Length)
{
int n = file.InputStream.Read(bytes, read, bytes.Length - read);
if (n <= 0) { break; }
read += n;
}
if (read != bytes.Length || ImageType(bytes) == null)
{
return new HttpStatusCodeResult(400, "Only PNG, JPEG, GIF and WebP images are taken.");
}
string id = Guid.NewGuid().ToString("N");
Images[id] = new KeyValuePair<DateTime, byte[]>(DateTime.UtcNow, bytes);
foreach (string old in Images.OrderByDescending(i => i.Value.Key).Skip(50).Select(i => i.Key).ToList()) { KeyValuePair<DateTime, byte[]> gone; Images.TryRemove(old, out gone); }
return Json(new { url = Url.Action("Image", new { id }) });
}
/// <summary>An uploaded image, by the id SaveImage gave it.</summary>
public ActionResult Image(string id)
{
KeyValuePair<DateTime, byte[]> image;
if (id == null || !Images.TryGetValue(id, out image)) { return HttpNotFound(); }
Response.Headers["X-Content-Type-Options"] = "nosniff";
return File(image.Value, ImageType(image.Value));
}
private static string ImageType(byte[] b)
{
if (b.Length > 8 && b[0] == 0x89 && b[1] == 0x50 && b[2] == 0x4E && b[3] == 0x47) { return "image/png"; }
if (b.Length > 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF) { return "image/jpeg"; }
if (b.Length > 6 && b[0] == 0x47 && b[1] == 0x49 && b[2] == 0x46 && b[3] == 0x38) { return "image/gif"; }
if (b.Length > 12 && b[0] == 0x52 && b[1] == 0x49 && b[2] == 0x46 && b[3] == 0x46 && b[8] == 0x57 && b[9] == 0x45 && b[10] == 0x42 && b[11] == 0x50) { return "image/webp"; }
return null;
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
@* Rich Text Editors with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@
The Rich Text Editor triggers the events based on its actions. The events can be used as an extension point to perform custom operations.
OnChange– Triggers when the editor gets blurred and changes are made to the content (or when the save interval has passed).OnFocus– Triggers when the editor is in focus.OnBlur– Triggers when focused out of the editor.OnActionBegin– Triggers before the execution of command.OnActionComplete– Triggers after the execution of command.OnCreated– Triggers when the component is created.OnBeforeDialogOpen,OnDialogOpenandOnDialogClose– Trigger as a dialog is being opened, is opened, and has been closed.OnBeforeQuickToolbarOpen,OnQuickToolbarOpenandOnQuickToolbarClose– Trigger as the quick toolbar is being opened, is opened, and has been closed.OnImageSelected– Triggers when the image is selected or dragged into the insert image dialog.OnImageUploading– Triggers when the selected image begins to upload in the insert image dialog.OnImageUploadSuccess– Triggers when the image is successfully uploaded to the server side.OnImageUploadFailed– Triggers when there is an error in the image upload.OnImageRemoving– Triggers when the selected image is cleared from the insert image dialog.OnResizing,OnResizeStartandOnResizeStop– Trigger while an image is resized (and when the editor is resized, withEnableResize).OnSelectionChanged– Triggers only when the selection within the editor is modified.OnDestroyedandOnBeforeSanitizeHtml– Trigger when the component is destroyed and before the value is sanitized.