# docx-editor-mail-merge

> Document editor demonstrating mail merge fields populated with recipient data.

**Framework:** aspnet-mvc  **Component:** DocxEditor  **Variant:** mail-merge

## Get this item

**If you are an agent, fetch the JSON.** Source is inlined, so one request is enough and no tooling is required:

```
GET https://ai.syncfusion.com/r/aspnet-mvc/docx-editor-mail-merge.json
```

**Install Package(s)**

```bash
Install-Package Syncfusion.AspNetMvc.DocumentEditor
Install-Package Syncfusion.AspNetMvc.Lists
Install-Package Syncfusion.AspNetMvc.Popups
```

**Notes**

- Syncfusion release: 2026 Volume 3 (v35.1.37)
- The Syncfusion package is licensed. The composition in this file is source you own and edit. See https://ai.syncfusion.com/licensing.md

## Source files

### src/components/docx-editor-mail-merge/DocxEditor.cshtml

```cshtml
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
    <div class="control-section" id="target">
        <div id='documenteditor_titlebar' class="e-de-ctn-title"></div>

        <div class="col-lg-2 control-section" style="padding-top: 5px;padding-right: inherit; padding-left: 5px;height:590px;border-left: 1px solid rgb(238, 238, 238);border-bottom: 1px solid rgb(238, 238, 238);">
            <h5><label style="display:block;margin:1px;padding-top: 5px">Select Field to Insert</label></h5>
            @Html.EJS().ListView("listview").DataSource((IEnumerable<object>)ViewData["dataSource"]).Fields(new ListViewFieldSettings { Tooltip = "Category" }).Render()
        </div>
        <div class="col-lg-10 control-section" style="padding-left:0px;padding-right:0px;padding-top:0px;">
            <div style="height:590px">
                @Html.EJS().DocumentEditorContainer("container").Height("590px").EnableToolbar(true).Render()
            </div>
        </div>

        @Html.EJS().Dialog("dialog").Header("Merge Field").Visible(false).FooterTemplate("<button id='addButton' class='e-control e-btn e-primary'>Insert</button><button id='cancelButton' class='e-control e-btn e-primary'>Cancel</button>").ShowCloseIcon(true).Width("300px").Target("#target").IsModal(true).ContentTemplate(@<input id='inVal' class='e-input' type='text' placeholder='Type a field to insert Eg. FirstName' />).Render()
        <div class="overlay" id="popup-overlay" style="display: none;"></div>
        <div id='waiting-popup' style="display: none;">
            <svg class="circular" height="40" width="40" role="none">
                <circle class="circle-path" cx="25" cy="25" r="20" fill="none" stroke-width="6" stroke-miterlimit="10" />
            </svg>
        </div>
    </div>
    <script src="~/Scripts/documenteditor/default-properties.js"></script>
}

@section Scripts{
    <script>
     var documenteditor;
     var contentChanged = false;
     var listview = document.getElementById("listview").ej2_instances[0];
     var dialogBox = document.getElementById("dialog").ej2_instances[0];
     document.addEventListener('DOMContentLoaded', function () {
         var documenteditorElement = document.getElementById("container");
         var container = documenteditorElement.ej2_instances[0];
         container.documentEditorSettings.showRuler = true;
         container.toolbarItems = [ 'New', 'Open', 'Separator', 'Undo',
            'Redo',
            'Separator',
            {
            prefixIcon: "sf-icon-InsertMergeField",
            tooltipText: "Insert Field",
            text: onWrapText("Insert Field"),
            id: "InsertField"
             },
             {

             prefixIcon: "sf-icon-FinishMerge",
             tooltipText: "Insert Field",
             text: onWrapText("Merge Document"),
             id: "MergeDocument"
             },
             'Separator',
            'Image',
            'Table',
            'Hyperlink',
            'Bookmark',
            'TableOfContents',
            'Separator',
            'Header',
            'Footer',
            'PageSetup',
            'PageNumber',
            'Break',
            'Separator',
            'Find',
            'Separator',
            'Comments',
            'TrackChanges',
            'Separator',
            'LocalClipboard',
            'RestrictEditing',
            'Separator',
            'FormFields',
            'UpdateFields'
             ];
         container.toolbarClick = function (args) {
             switch (args.item.id) {
                 case 'MergeDocument':
                     mergeDocument();
                     break;
                 case 'InsertField':
                     showInsertFielddialog();
                     break;
             }
         };
         documenteditor = container.documentEditor;
         documenteditorElement.ej2_instances[0].serviceUrl = window.baseurl + 'api/documenteditorservice/';
         documenteditor.serviceUrl = window.baseurl + 'api/documenteditorservice/';
         var ajax = new ej.base.Ajax("@Url.Content("~/scripts/documenteditor/data-mailmerge.json")", 'GET', true);
         ajax.send().then();
         ajax.onSuccess = function (data) {
             documenteditor.open(data);
             documenteditor.documentName = 'Mail Merge';
             updateDocumentTitle();
         };
         titleBarDiv = document.getElementById('documenteditor_titlebar');
         initComponentAndWireEvent();

         container.documentChange = function () {
             updateDocumentTitle();
             documenteditor.focusIn();
         };
         // Add drag start element for list view
         document.getElementById("listview").addEventListener("dragstart", function (event) {
             event.dataTransfer.setData("Text", event.target.innerText);
             event.target.classList.add('de-drag-target');

         });

         // Prevent default drag over for document editor element
         document.getElementById("container").addEventListener("dragover", function (event) {
             event.preventDefault();
         });

         // Drop Event for document editor element
         document.getElementById("container").addEventListener("drop", function (e) {
             console.log(this);
             var text = e.dataTransfer.getData('Text').replace(/\n/g, '').replace(/\r/g, '').replace(/\r\n/g, '');
             documenteditor.selection.select({ x: e.offsetX, y: e.offsetY, extend: false });
             container.documentEditor.editor.insertField('MERGEFIELD ' + text + ' \\* MERGEFORMAT');
         });

         document.addEventListener("dragend", function (event) {
             if (event.target.classList.contains('de-drag-target')) {
                 event.target.classList.remove('de-drag-target');
             }
         });
         function onWrapText(text) {
        let content = '';
        let index = text.lastIndexOf(' ');
        content = text.slice(0, index);
        text.slice(index);
        content += '<div class="e-de-text-wrap">' + text.slice(index) + '</div>';
        return content;
         }

         //Click Event
         listview.addEventListener("select", function (args) {
             var fieldName = args.text;
             if (fieldName !== '') {
                 container.documentEditor.editor.insertField('MERGEFIELD ' + fieldName + ' \\* MERGEFORMAT');
             }
             dialogBox.hide();
             container.documentEditor.focusIn();
         });

        function showInsertFielddialog() {
            dialogBox.show();
        }
        document.getElementById('addButton').onclick = function (e) {
            addField();
        };
        document.getElementById('cancelButton').onclick = function (e) {
            cancelDialog();
        };

        function addField() {
            let fieldNameTextBox = document.getElementById('inVal');
            var fieldName = fieldNameTextBox.value;
            if (fieldName !== '') {
                container.documentEditor.editor.insertField('MERGEFIELD ' + fieldName + ' \\* MERGEFORMAT');
            }
            dialogBox.hide();
            container.documentEditor.focusIn();
        };
        function cancelDialog() {
            var dialogBox = document.getElementById("dialog").ej2_instances[0];
            dialogBox.hide();
        };

         function mergeDocument() {
             documenteditor.saveAsBlob("Docx").then(function (blob) {
                 var fileReader = new FileReader();
                 fileReader.onload = function () {
                     var base64String = fileReader.result;
                     var data = {
                         fileName: documenteditor.documentName + '.docx',
                         documentData: base64String
                     }
                     showHideWaitingIndicator(true)
                     var httpRequest = new XMLHttpRequest();
                     httpRequest.open('Post', window.baseurl + 'api/documenteditorservice/MailMerge', true);
                     httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                     httpRequest.onreadystatechange = function () {
                         if (httpRequest.readyState === 4) {
                             if (httpRequest.status === 200 || httpRequest.status === 304) {
                                 documenteditor.open(httpRequest.responseText);
                             } else {
                                 // Failed to merge document
                                 ejs.popups.DialogUtility.alert({
                        title: 'Information',
                        content: 'Failed to merge document.',
                        showCloseIcon: true,
                        closeOnEscape: true,
                    });
                             }
                             showHideWaitingIndicator(false);
                         }
                     };
                     httpRequest.send(JSON.stringify(data));
                 }
                 fileReader.readAsDataURL(blob);
             });
         }
     });
        function showHideWaitingIndicator(show) {
            document.getElementById("popup-overlay").style.display = show ? 'block' : 'none';
            document.getElementById("waiting-popup").style.display = show ? 'block' : 'none';
        }

    </script>

}

<style>
    #documenteditor_titlebar {
        border-bottom: 1px solid #2B3481;
        height: 36px;
        line-height: 26px;
        width: 100%;
        font-size: 12px;
        padding-left: 15px;
        padding-right: 10px;
        font-family: inherit;
    }

    #documenteditor_title_contentEditor {
        height: 26px;
        max-width: 85%;
        width: auto;
        overflow: hidden;
        display: inline-block;
        padding-left: 4px;
        padding-right: 4px;
        margin: 5px;
    }

    .overlay {
        z-index: 10;
        display: none;
        position: absolute;
        background-color: #383838;
        height: 100%;
        width: 100%;
        opacity: .5;
        left: 0;
        top: 0;
        bottom: 0;
    }

    #waiting-popup {
        width: 56px;
        height: 56px;
        position: absolute;
        top: calc(50% - 28px);
        left: calc(50% - 28px);
        border-radius: 50%;
        padding: 3px;
        overflow: hidden;
        background-position: center;
        background-color: white;
        z-index: 20;
        display: none;
    }

    .circular {
        animation: rotate 2s linear infinite;
        height: 50px;
        width: 50px;
        border-radius: 50%;
    }

    .circle-path {
        stroke-dasharray: 1, 200;
        stroke-dashoffset: 0;
        animation: dash 1.5s ease-in-out infinite, color 6s ease-in-out infinite;
        stroke-linecap: round;
        stroke: #ff4081;
    }

    @@keyframes rotate {
        100% {
            transform: rotate(360deg);
        }
    }

    @@keyframes dash {
        0% {
            stroke-dasharray: 1, 200;
            stroke-dashoffset: 0;
        }

        50% {
            stroke-dasharray: 89, 200;
            stroke-dashoffset: -35;
        }

        100% {
            stroke-dasharray: 89, 200;
            stroke-dashoffset: -124;
        }
    }

    .single-line {
        cursor: text !important;
        outline: none;
    }

    .heading-section {
        padding-bottom: 20px;
        padding-top: 20px;
    }

    .single-line:hover {
        border-color: #e4e4e4 !important;
    }

    [contenteditable="true"].single-line {
        white-space: nowrap;
        border-color: #e4e4e4 !important;
    }

    /** Document editor sample level font icons*/

    @@font-face {
        font-family: 'Sample brower icons';
        font-weight: normal;
        font-style: normal;
    }

    [class^="e-de-icon-"],
    [class*=" e-de-icon-"] {
        font-family: 'Sample brower icons' !important;
    }

    .e-de-icon-Print:before {
        content: "\e723";
    }

    .e-de-icon-Download:before {
        content: "\e728";
    }

    .e-btn-hide {
        display: none;
    }

    .Table {
        border-collapse: separate;
        border-spacing: 10px;
        width: 85%;
        margin: 0px -5px 0px;
    }

    @@font-face {
        font-family: 'Font Mail merge icon';
        font-weight: normal;
        font-style: normal;
    }

    [class^="sf-icon-"], [class*=" sf-icon-"] {
        font-family: 'Font Mail merge icon' !important;
        color: rgba(0, 0, 0, 0.54);
        font-weight: 600;
        font-size: 14px;
    }

    .sf-icon-FinishMerge:before {
        content: "\e700";
    }

    .sf-icon-InsertMergeField:before {
        content: "\e701";
    }
</style>

```

### src/components/docx-editor-mail-merge/DocxEditorController.cs

```cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EJ2MVCSampleBrowser.Controllers.DocumentEditor
{
    public partial class DocumentEditorController : Controller
    {
        public ActionResult MailMerge()
        {
            this.DocumentEditorViewResultHelper();
            List<object> listdata = new List<object>();
            listdata.Add(new
            {
                text = "ProductName",
                id = "_productname",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "ShipName",
                id = "_shipname",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "CustomerID",
                id = "_customerid",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "Quantity",
                id = "_quantity",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "UnitPrice",
                id = "_unitprice",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "Discount",
                id = "_discount",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "ShipAddress",
                id = "_shipaddress",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "ShipCity",
                id = "_shipcity",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            listdata.Add(new
            {
                text = "ShipCountry",
                id = "_shipcountry",
                Category = "Drag or click the field to insert.",
                htmlAttributes = new { draggable = true }
            });
            ViewData["dataSource"] = listdata;
            return View("~/Views/Home/docx-editor/mail-merge/DocxEditor.cshtml");
        }

    }
}

```
