Integrating TinyMCE into an MVC 5 Project

I thought I would take some time to address a question that has frequently appeared in a few forum questions over the past month or so and that is “How do I use the TinyMCE Editor within ASP.NET MVC?”.

Since I’ve answered this quite a few times, I thought I would take a few minutes to share the process with the rest of the net so prevent this from popping up in the future.

Let’s address a few of the extremely common questions.

Can I use TinyMCE with ASP.NET MVC? Or Web Forms?

Of course you can. TinyMCE is simply a pure Javascript rich text editor that has no reliance on MVC, Web Forms or any other server-side related technology. All you need to use it is some simple HTML markup and the appropriate TinyMCE Javascript and content files (which are included within the download).

How or where can I download TinyMCE?

The easiest approach would be to download the latest TinyMCE package via NuGet through the following steps :

  • Right-click on your Project.
  • Choose Manage NuGet Packages from the Context menu.
  • Select the Online tab on the left within the dialog box.
  • Search for “TinyMCE” in the upper right-hand corner.
  • Install the TinyMCE package to your project.

If you aren’t using ASP.NET or simply do not have access to NuGet, you can always visit the TinyMCE site and download the latest version of the editor from there.

A Simple Walkthrough for Getting Started with TinyMCE

Let’s create a simple new MVC 5 Application through Visual Studio. For simplicity’s sake, I’ll just be using an Empty Project with the appropriate MVC references added :

Next, you’ll need some way to access the TinyMCE files. Two of the most common approaches (downloading the NuGet package or directly downloading from TinyMCE) are detailed above, this example will use the NuGet approach, but both of them should be similar.

You should now see several new files within a newly created ~/scripts/tinymce folder. This folder contains everything that you need to use and configure the TinyMCE editor.

In order to actually use the editor, you’ll need to create a Controller with a single action that points to a View. For all intents and purposes, we will call this one TinyMCEController and it will have an action called “Index” and another Index action that is decorated with an [HttpPost] attribute (and will accept a class that we will define below) :

public class TinyMCEController : Controller
{
        // An action to display your TinyMCE editor
        public ActionResult Index()
        {
            return View();
        }

        // An action that will accept your Html Content
        [HttpPost]
        public ActionResult Index(ExampleClass model)
        {
            return View();
        }
}

Next, let’s actually flesh out this very simple class that will just have a single, but very important property and an even more important [AllowHtml] attribute decorating it :

// An example class to store your values
public class ExampleClass
{
        // This attributes allows your HTML Content to be sent up
        [AllowHtml]
        public string HtmlContent { get; set; } 

        public ExampleClass()
        {

        }
}

The [AllowHtml] attribute is going to by-pass ASP.NET serialization protection (which can aid in preventing nasty XSS or any other types of garbage input that might fly on it). Without this attribute, you would need to disable RequestValidation for the specified action which is a bit overkill in this scenario as you just need to check for HTML.

The next step will be to add a View that targets your Index action. Right-click on your Index Controller Action and choose the available Add View… option that appears in the context menu. In this example, we won’t be using a Layout page or a Template, so you can leave those options :

After generating your View, you’ll need to add a few references in to target and configure your TinyMCE scripts. You’ll also need a very simple <form> element to post your content from the TinyMCE editor as detailed below :

<!-- This View uses your Model -->
@model TinyMCE.Controllers.ExampleClass
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>TinyMCE Example</title>
    <!-- TinyMCE Script Reference -->
    <script src="~/scripts/tinymce/tinymce.min.js"></script>
    <!-- Script to wire up your TinyMCE editor -->
    <script type="text/javascript">
        // Initialize your tinyMCE Editor with your preferred options
        tinyMCE.init({
            // General options
            mode: "textareas",
            theme: "modern",
            // Theme options
            theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,

            // Example content CSS (should be your site CSS)
            content_css: "css/example.css",
        });
    </script>
</head>
<body>
    <!-- This will automatically post to your Index method (that is decorated with a HttpPost attribute) -->
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        <div>
            <!-- This will contain your HtmlContent and use the TinyMCE editor-->
            @Html.TextAreaFor(model => model.HtmlContent)
           
            <input type="submit" value="Create" />
        </div>
    }
</body>
</html>

Obviously, the configuration code that is used above within the <script> tag might look a bit overwhelming. You can visit the TinyMCE Examples page which demonstrates a few varying levels and features depending on your needs.

After adding your View in, you should be able to run your application and see the following :

Once you hit the Create button within the View, your content will be posted with its associated markup to your Controller and you should be able to see it without any issues :

Alternatives and Other Editors

Although this walk-through explicitly targeted the TinyMCE editor, it is my no means limited to just it. The same basic steps should work with any of the popular client-side Rich Text Editors such as Redactor, CKEditor, HTML Editor and more. You’ll just need to include the proper references and content files and ensure that you are targeting the proper element when using the configuration code.

It should be noted that there are a variety of other NuGet packages out there for using TinyMCE as well if this felt like too much of a hassle. The TinyMCE.MVC relies on an HTML Helper to build and wire up your editors for specific areas and can be useful if you don’t like messing with Javascript at all. It’s just a matter of preference.