Monday, June 2, 2014

Step by Step how to use the TinyMCE Rich Editor as template for the UIHint DataAnnotation Attribute

        By Carmel Shvartzman

In this tutorial we'll learn how to use the TinyMCE Rich Editor as a  template for the UIHintAttribute DataAnnotation
We'll use a FREE MCE Editor , adding it through NUGET Package Manager. The MCE will be stored as a Template at "~/Views/Shared/EditorTemplates", and we'll use DataAnnotations to display the Rich Editor in our MVC App.
According to the  MSDN  documentation , UIHint receives as an argument the template or user control that Dynamic Data will use to display the data field. While using the UIHint attribute on the Model, and the EditorFor or DisplayFor inside a view, the ASP.NET MVC engine will look for the specified template at the "~/Views/Shared/EditorTemplates" directory.
You can take a look at the MSDN  documentation and description of the UIHintAttribute . It was originally introduced for Dynamic Data , and later for ASP.NET MVC.
We'll design a web site using a free CSS Template, as explained in a former tutorial, and a JQuery UI Theme that we imported in this tutorial. They are short step by step begginer's guides, so if you like the look-and-feel of this web site, follow those 10 minutes tutorials to make this same site.We'll want to display our data using a TinyMCE, showing as follows:
In the field "Text" we will format the font, and also insert pictures. First thing, download the MCR Editor using NUGET making a search for "TinyMCE.MVC.JQuery" :

Also, update the JQuery and the JQueryUI scripts:

You'll notice that NUGET added files to the Scripts folder:

And also added a TEMPLATE to the "Shared" folder:

Open the TinyMCE Template and modify the WIDTH & HEIGHT:

Check for the JQuery scripts at _Layout, because TinyMCE needs the .js BEFORE loading the document:

This is the field we want to turn from Text to Rich Editor:

The name of the field is "Text" and the Entity is "Comment" :

Take a look at the Comment class:

We cannot modify the auto-generated template , so let's EXTEND the class with a METADATA partial class:

We need to make a Data Annotation to ONLY one field : "Text" . So use the UIHintAttribute and send the Template argument the name of the TinyMCE template file at the SHARED folder.
Build and run the App to see the Rich Editor:

You can insert a picture as well:

After saved, you'll see the field is not properly displayed :

We must modify the displaying of the field :

...using the Raw() method for displaying the HTML :

Now this is the display :

That's all!! 
In this tutorial we've learned how to use the TinyMCE Rich Editor as a  template for the UIHint DataAnnotation Attribute.  

Happy programming.....

כתב: כרמל שוורצמן