Example of Ajax Content in ASP.NET MVC Rich Text Editor Control
This sample demonstrates how to load content to the editor from an external source using Fetch library .
@Html.UiRichTextEditor(new UiRichTextEditorOptions
{
Id = "ajaxEditor",
Name = "Ajax",
Height = "300px",
Placeholder = "Choose an article above."
})
<div class="rte-actions">
<button type="button" class="btn btn-outline-secondary btn-sm" data-rte-topic="intro">Getting started</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-rte-topic="release">Release notes</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-rte-topic="unsafe">An unsafe article</button>
</div>
@Html.UiRichTextEditor(new UiRichTextEditorOptions
{
Id = "ajaxEditor",
Name = "Ajax",
Height = "300px",
Placeholder = "Choose an article above."
})
<p class="small mt-2" id="rteAjaxStatus" role="status"></p>
<style>
.rte-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }
</style>
<script>
(function () {
'use strict';
function status(text) {
document.getElementById('rteAjaxStatus').textContent = text;
}
document.addEventListener('click', function (event) {
var button = event.target.closest('[data-rte-topic]');
if (!button) { return; }
var token = document.querySelector('input[name="__RequestVerificationToken"]');
status('Loading...');
fetch('/RichTextEditorDemo/AjaxContent', {
method: 'POST',
headers: { 'Content-Type': 'application/json', RequestVerificationToken: token ? token.value : '' },
body: JSON.stringify({ topic: button.getAttribute('data-rte-topic') })
}).then(function (response) {
if (!response.ok) { throw new Error('HTTP ' + response.status); }
return response.json();
}).then(function (answer) {
// The server made it safe; the editor makes it safe again as it takes it.
window.Lumen.get('ajaxEditor').value = answer.html;
status('Loaded "' + button.textContent + '".');
}).catch(function () {
status('The article could not be loaded.');
});
});
})();
</script>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace YourApp.Controllers
{
public class RichTextEditorController : Controller
{
// The page is Views/RichTextEditor/AjaxContent.cshtml; it draws what ViewData holds.
public ActionResult AjaxContent()
{
return View();
}
private static readonly Dictionary<string, string> Articles = new Dictionary<string, string>
{
{ "intro", "<h2>Getting started</h2><p>The editor's content came from <b>the server</b>, after the page was loaded.</p><ul><li>Fetched with the anti-forgery token</li><li>Made safe on the server</li><li>Set with <code>editor.value</code></li></ul>" },
{ "release", "<h2>Release notes</h2><p>Version <i>2.4</i> adds tables and links.</p><table><tbody><tr><td>Tables</td><td>Insert, add and remove rows and columns</td></tr><tr><td>Links</td><td>Insert, edit, open in a new window</td></tr></tbody></table>" },
{ "unsafe", "<p>This text came with a script and an event handler; the server removed both.</p><script>window.x=1</script><img src=x onerror=\"window.x=1\"><p onclick=\"window.x=1\">Click me</p>" }
};
/// <summary>The Ajax Content sample's articles: JSON { topic } in, { html } out (the HTML made safe by UiHtmlSanitizer).</summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult AjaxContent()
{
string body;
Request.InputStream.Position = 0;
using (var reader = new StreamReader(Request.InputStream)) { body = reader.ReadToEnd(); }
var request = JsonConvert.DeserializeObject<ContentRequest>(body);
string html;
if (request == null || request.Topic == null || !Articles.TryGetValue(request.Topic, out html))
{
return new HttpStatusCodeResult(400, "Unknown topic.");
}
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
return Content(JsonConvert.SerializeObject(new { html = UiHtmlSanitizer.Sanitize(html) }, settings), "application/json");
}
private sealed class ContentRequest
{
public string Topic { get; set; }
}
}
}
@* 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 allows you to load content from an external source. The sample content is loaded from “Ajax_content.html” file using Fetch library, and when the event is successful the content will be loaded into the editor using value property.