Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Integrating TinyMCE into an MVC 5 Project

0.00/5 (No votes)
18 Oct 2014 1  
How to integrate TinyMCE into an MVC 5 project

TinyMCEHeader

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 to 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 Walkthough 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:

Create a new Empty Project with the appropriate MVC references.

Create a new Empty Project with the appropriate MVC references.

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.

Use the NuGet Package Manager to easily install the TinyMCE Package

Use the NuGet Package Manager to easily install the TinyMCE Package

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 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 of an 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:

You'll just need to create a very basic View without any templating or Layouts. Usage may vary.

You’ll just need to create a very basic View without any templating or Layouts. Usage may vary.

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:

Editor

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:

Posted

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here