Save Rich Text Editor content in a file in the server

1 Mar 20224 minutes to read

Rich Text Editor content can be passed from view to controller through XMLHttpRequest post. Content will be sent to the corresponding method into the controller and this value can be saved in a text file or any other format using streamWriter. Refer to the following given code.

<div>
    <div>
        @Html.EJS().RichTextEditor("saveFile").ContentTemplate(@<div>
            <p>
                The Rich Text Editor control is 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 &lt; IFRAME &gt; and &lt; DIV &gt; 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 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>
        </div>).Render()
    </div>
    <div> <button id="btn">save content</button></div>
</div>

<script>
    document.getElementById('btn').addEventListener('click', function () {
    var obj = document.getElementById('saveFile').ej2_instances[0];
  var value = JSON.stringify({ text: obj.value });
  const Http = new XMLHttpRequest();
  const url = '@Url.Action("Save")';
    Http.open("POST", url);
    Http.setRequestHeader('Content-Type', 'application/json');
    Http.send(value);
 });
</script>
public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public class RichTextEditorValue
        {
            public string text { get; set; }
        }
        [HttpPost]
        public ActionResult Save([System.Web.Http.FromBody]RichTextEditorValue value)
        {
            string RootPath = Server.MapPath("~/data.txt");
            StreamWriter writeFile = new StreamWriter(RootPath, true);
            writeFile.WriteLine(value.text);
            writeFile.Close();
            writeFile.Dispose();
            return View();
        }

    }