Search code examples
javascriptjqueryasp.net-mvcasp.net-corequill

How do I store a DIV value? (Quill)


Problem: When I add text to the DIV (Quill TextEditor) and hit the save button, I notice that the text isn't saved in the database. The DIV is supposed to hold the value for my Model's Description property.

How can I solve this?

View:

<div class="form-group">
    <label asp-for="Description" class="control-label"></label>
    <div id="editor-container" asp-for="Description" class="form-control"></div>
    <span asp-validation-for="Description" class="text-danger"></span>
    <script>
        var quill = new Quill('#editor-container', {
            modules: {
                toolbar: [
                    [{ header: [1, 2, false] }],
                    ['bold', 'italic', 'underline'],
                    ['image', 'code-block']
                ]
            },
            placeholder: 'Compose an epic...',
            theme: 'snow'  // or 'bubble'
        });
    </script>
</div>

Solution

  • Since DIV's are not input elements I added an INPUT element and made it hidden type="hidden". Through JavaScript I populated the INPUT element with Quilljs Editor value when the user hits the Submit button.

    This is how I solved it.

    <div class="form-group">
        <label asp-for="Description" class="control-label"></label>
        <input asp-for="Description" name="Description" type="hidden" class="form-control" />
        <div id="editor-container" name="editor-container"></div>
        <span asp-validation-for="Description" class="text-danger"></span>
        <script>
            var quill = new Quill('#editor-container', {
                modules: {
                    toolbar: [
                        ['bold', 'italic'],
                        ['link', 'blockquote', 'code-block', 'image'],
                        [{ list: 'ordered' }, { list: 'bullet' }]
                    ]
                },
                placeholder: 'Compose an epic...',
                theme: 'snow'
            });
    
            var form = document.querySelector('form');
            form.onsubmit = function () {
                // Populate hidden form on submit
                var description = document.querySelector('input[name=Description]');
                description.value = JSON.stringify(quill.getContents());
    
                console.log("Submitted", $(form).serialize(), $(form).serializeArray());
            };
        </script>
    </div>