How to integrate TinyMCE with ASP.NET MVC

3

Implementing TinyMCE into ASP.NET MVC encountered a problem uploading images .

The form I'm trying to implement is as follows:

I have a View with Script that calls a Controller containing a upload method that does its job saving the image to my server, as it is a common method and is working perfectly, I left it in the Gist , in order to shorten the question a little. And my View :

@model EuVotoAf.Models.Publicacao

@{
    ViewBag.Title = "Create";

}
<script src="~/Scripts/tinymce/tinymce.js"></script>
<h2>Create</h2>

<iframe id="form_target" name="form_target" style="display:none"></iframe>

@using (Html.BeginForm("Upload", "Publicacao", FormMethod.Post, new { @id = "my_form", target = "form_target", enctype = "multipart/form-data", style = "width:0;height:0;overflow:hidden" }))
{
    @Html.AntiForgeryToken()
    <input name="file" type="file" onchange="$('#my_form').submit();this.value='';">
}


<script type="text/javascript">
    tinymce.init({
        selector: "textarea",
        theme: "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern imagetools"
        ],
        toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
        toolbar2: "print preview media | forecolor backcolor emoticons | ltr rtl",
        image_advtab: true,
        templates: [
            { title: 'Test template 1', content: 'Test 1' },
            { title: 'Test template 2', content: 'Test 2' }
        ],
        file_browser_callback: function (field_name, url, type, win) {
            if (type == 'image') $('#my_form input').click();
        }
    });
</script>

@Html.TextAreaFor(model => model.Conteudo, new { id = "my_editor", @class = "mceEditor" })

@using (Html.BeginForm("Create", "Publicacao", FormMethod.Post))
{
    @Html.AntiForgeryToken()


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}

What I basically need is to send the text to be saved in DB and the image to be saved on the server. If I put the line

@Html.TextAreaFor(model => model.Conteudo, new { id = "my_editor", @class = "mceEditor" })

Within the first form it does not render on the screen, if I put it in the second, the upload is not done. Which is the way I can make it work in some way.

Am I doing the wrong thing?

That's right, but does it contain errors in the code?

Is there a better way to do it?

If you have any other important details that I did not enter, I can put it.

    
asked by anonymous 30.01.2017 / 23:44

1 answer

4

I will not talk much about TinyMCE, but about its problems and a generic way of solving it.

First, you have two forms on the same page. Even using Ajax indirectly , you may have some problems.

Another thing, do not put scripts in the middle of the View. You have section only for her.

And your biggest problem. TinyMCE is not in%% of%. In summary, sending the form form will not send the value of @using (Html.BeginForm("Create", "Publicacao", FormMethod.Post)) .

Well, now let's go to the generic solution.

First, update your View for this:

<h2>Create</h2>


<input name="file" type="file" id="file">

@using (Html.BeginForm("Create", "Publicacao", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.TextAreaFor(model => model.Conteudo, new { id = "my_editor", @class = "mceEditor" })

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}

@section Scripts{
    <script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
    <script type="text/javascript">
        tinymce.init({
            selector: "textarea",
            theme: "modern",
            plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table contextmenu directionality",
                "emoticons template paste textcolor colorpicker textpattern imagetools"
            ],
            toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
            toolbar2: "print preview media | forecolor backcolor emoticons | ltr rtl",
            image_advtab: true,
            templates: [
                { title: 'Test template 1', content: 'Test 1' },
                { title: 'Test template 2', content: 'Test 2' }
            ],
            file_browser_callback: function (field_name, url, type, win) {
                if (type == 'image') $('#my_form input').click();
            }
        });
    </script>

    <script>
        $('#file').change(function () {
            var formData = new FormData();
            var file = this.files[0];
            console.log(file)
            formData.append('file', file);
            $.ajax({
                url: '@Url.Action("Upload", "Home")',  
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log(data)
                    tinyMCE.get('my_editor').setContent('dsdsdsds');
                    tinymce.activeEditor.execCommand('mceInsertContent', false, data);
                }
            });
        });
    </script>
}

And your Controller for this:

  public string Upload(HttpPostedFileBase file)
    {
        string path;
        string saveloc = "~/Uploads/Imagens";
        string filename = file.FileName;

        if (file != null && file.ContentLength > 0)
        {
            try
            {
                path = Path.Combine(HttpContext.Server.MapPath(saveloc), Path.GetFileName(filename));
                file.SaveAs(path);
            }
            catch (Exception e)
            {
                return "<script>alert('Failed: " + e + "');</script>";
            }
        }
        else
        {
            return "<script>alert('Failed: Unkown Error. This form only accepts valid images.');</script>";
        }

        return @"<img src=/Uploads/Imagens/" + filename + " >";
    }

Note that I'm now doing Upload in the change () event. After that, I send the file to the Controller via Ajax and the return I enter in TinyMCE, through Conteudo .

Note that the return of the Controller is no longer a script, but a tinymce.activeEditor.execCommand('mceInsertContent', false, data); image. I made it this way because if you change the WYSIWYG , the code can remain the same.

Now, if you want to add the upload to the insert / edit image button, things change a little.

    
31.01.2017 / 01:16