Click here to Skip to main content
15,867,330 members
Articles / MVC / MVC5

Integrating TinyMCE into an MVC 5 Project

Rate me:
Please Sign up or sign in to vote.
4.47/5 (8 votes)
18 Oct 2014CPOL4 min read 63.2K   12   9
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):

C#
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:

C#
// 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:

HTML
<!-- 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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
An experienced Software Developer and Graphic Designer with an extensive knowledge of object-oriented programming, software architecture, design methodologies and database design principles. Specializing in Microsoft Technologies and focused on leveraging a strong technical background and a creative skill-set to create meaningful and successful applications.

Well versed in all aspects of the software development life-cycle and passionate about embracing emerging development technologies and standards, building intuitive interfaces and providing clean, maintainable solutions for even the most complex of problems.

Comments and Discussions

 
QuestionQueries Pin
Member 145196434-Oct-19 20:13
Member 145196434-Oct-19 20:13 
QuestionIs there any possiple to save the html content using save dialog box? Pin
smksamy30-Oct-17 20:16
smksamy30-Oct-17 20:16 
Hi Friend,
I used this TinyMCe in my project, I need to save the output content using Save dialog box. but, it saves the document like a downloaded file. is there any possible.
Questionhtml content not rendering with applied inline css after postback Pin
Er. Shailesh13-Mar-17 20:41
Er. Shailesh13-Mar-17 20:41 
QuestionAMAZING!! Pin
RashaSalim16-Jan-17 9:49
RashaSalim16-Jan-17 9:49 
QuestionI moved the script block into a separate JS file, added the reference to BundleConfig in my MVC project, it doesn't seem working Pin
Member 1220988415-Dec-15 13:40
Member 1220988415-Dec-15 13:40 
AnswerRe: I moved the script block into a separate JS file, added the reference to BundleConfig in my MVC project, it doesn't seem working Pin
Member 1220988415-Dec-15 14:06
Member 1220988415-Dec-15 14:06 
GeneralNice Pin
Ramchandra Magar24-Sep-15 1:15
Ramchandra Magar24-Sep-15 1:15 
QuestionError Pin
birmsi15-Dec-14 4:00
birmsi15-Dec-14 4:00 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)29-Oct-14 20:10
Shemeemsha (ഷെമീംഷ)29-Oct-14 20:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.