Using Rich Text Editor (WYSIWYG) in ASP.NET MVC

   Introduction:

          In ASP.NET MVC forum I found some question regarding a sample HTML Rich Text Box Editor(also known as wysiwyg).So i decided to create a sample ASP.NET MVC web application which will use a Rich Text Box Editor. There are are lot of Html Editors are available, but for creating a sample application, i decided to use cross-browser WYSIWYG editor from openwebware. In this article I will discuss what changes needed to work this editor with ASP.NET MVC. Also I had attached the sample application for download at http://www.speedfile.org/155076. Also note that I will only show the important features, not discuss every feature in detail.

   Description:

          So Let's start create a sample ASP.NET MVC application. You need to add the following script files,
 

        jquery-1.3.2.min.js
        jquery_form.js
        wysiwyg.js
        wysiwyg-settings.js
        wysiwyg-popup.js



          Just put these files inside Scripts folder. Also put wysiwyg.css in your Content Folder and add the following folders in your project

        addons
        popups



          Also create a empty folder Uploads to store the uploaded images. Next open wysiwyg.js and set your configuration

         

        // Images Directory
        this.ImagesDir = "/addons/imagelibrary/images/";
       
        // Popups Directory
        this.PopupsDir = "/popups/";
       
        // CSS Directory File
        this.CSSFile = "/Content/wysiwyg.css";   



          Next create a simple View TextEditor.aspx inside View / Home Folder and add the folllowing HTML.

        <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
   
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <html xmlns="http://www.w3.org/1999/xhtml" >
            <head runat="server">
                <title>TextEditor</title>
                <script src="../../Scripts/wysiwyg.js" type="text/javascript"></script>
                <script src="../../Scripts/wysiwyg-settings.js" type="text/javascript"></script>
                <script type="text/javascript">       
                    WYSIWYG.attach('text', full);           
                </script>
            </head>
            <body>
                <% using (Html.BeginForm()){ %>
                    <textarea id="text" name="test2" style="width:850px;height:200px;">
                    </textarea>
                    <input type="submit" value="submit" />
                <%} %>
            </body>
        </html>


       
          Here i have just added a text area control and a submit button inside a form. Note the id of text area and WYSIWYG.attach function's first parameter is same and next to watch is the HomeController.cs


        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;
        using System.IO;

        namespace HtmlTextEditor.Controllers
        {
            [HandleError]
            public class HomeController : Controller
            {
                public ActionResult Index()
                {
                    ViewData["Message"] = "Welcome to ASP.NET MVC!";

                    return View();
                }
   
                public ActionResult About()
                {           
                    return View();
                }
       
                public ActionResult TextEditor()
                {
                    return View();
                }
                [AcceptVerbs(HttpVerbs.Post)]
                [ValidateInput(false)]
                public ActionResult TextEditor(string test2)
                {
                    Session["html"] = test2;
       
                    return RedirectToAction("Index");
                }
       
                public ActionResult UploadImage()
                {
                    if (Request.Files[0].FileName != "")
                    {
                        Request.Files[0].SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(Request.Files[0].FileName)));
                        return Content(Url.Content("~/Uploads/" + Path.GetFileName(Request.Files[0].FileName)));
                    }
                    return Content("a");
                }
            }
        }




          So simple code, just save the posted Html into Session. Here the parameter of TextArea action is test2 which is same as textarea control name of TextArea.aspx View. Also note ValidateInputAttribute is false, so it's up to you to defends against XSS. Also there is an Action method which simply saves the file inside Upload Folder.

          I am uploading the file using Jquery Form Plugin. Here is the code which is found in insert_image.html inside addons folder,

        function ChangeImage() {
            var myform=document.getElementById("formUpload");       
            $(myform).ajaxSubmit({success: function(responseText){
                insertImage(responseText);
                        window.close();
                }
            });
        }



          and here is the Index View which simply renders the html of Editor which was saved in Session

        <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

        <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
            Home Page
        </asp:Content>

        <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
            <h2><%= Html.Encode(ViewData["Message"]) %></h2>
            <p>
                To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
            </p>
            <%if (Session["html"] != null){
                  Response.Write(Session["html"].ToString());
            } %>   
       
        </asp:Content>


   Summary:

          Hopefully you will enjoy this article. Just download the code and see the effect. From security point, you must handle the XSS attack your self. I had uploaded the sample application in http://www.speedfile.org/155076

12 Comments

Comments have been disabled for this content.