Products Technologies Demo Docs Blog Support Company

MVC: Merging Templates in a Controller HttpPost Method

The MailMerge engine and Web.TextControl combine to merge templates server-side in an MVC application. A JavaScript function saves the document as a Base64 string, posts it to an HttpPost controller method, merges it with a DataSet, and loads the result back into the editor.

MVC: Merging Templates in a Controller HttpPost Method

The reporting engine MailMerge is used to merge templates with data. In combination with the HTML5 based MVC editor Web.TextControl, the created template can be merged in the MVC controller and loaded back into the view.

The following HttpPost method Merge accepts the model DocumentViewModel which contains the template encoded as a Base64 string. The data source is loaded into a new DataSet object. Finally, the template is loaded into a new instance of the MailMerge class and merged with the loaded DataSet. The created document is returned to the view.

[HttpPost]
public string Merge(DocumentViewModel model)
{
    // convert the template to a byte array
    byte[] document = 
        Convert.FromBase64String(model.BinaryDocument);

    // load the the data source
    DataSet ds = new DataSet();
    ds.ReadXml(Server.MapPath("/App_Data/data/sample_db.xml"),
        XmlReadMode.Auto);

    byte[] sDocument;

    // create a new ServerTextControl and MailMerge component
    using (TXTextControl.ServerTextControl tx =
        new TXTextControl.ServerTextControl())
    {
        MailMerge mm = new MailMerge();
        mm.TextComponent = tx;

        // load the template and merge
        mm.LoadTemplateFromMemory(document, 
            FileFormat.InternalUnicodeFormat);
        mm.Merge(ds.Tables[0], true);

        // save the document
        mm.SaveDocumentToMemory(out sDocument, 
            TXTextControl.BinaryStreamType.InternalUnicodeFormat, null);
    }

    // encode and return the merged document
    return Convert.ToBase64String(sDocument);
}

The contoller method is called from the Javascript function Merge. The current document is saved into a Base64 encoded string and is being sent using AJAX to the controller method Merge.

When the controller method returns successfully, the merged document is loaded into the editor.

function Merge() {
    // save the document
    TXTextControl.saveDocument(
        TXTextControl.streamType.InternalUnicodeFormat,
        function (e) {

            var serviceURL = "/Home/Merge";

            // call the controller
            $.ajax({
                type: "POST",
                url: serviceURL,
                contentType: 'application/json',
                data: JSON.stringify({
                    BinaryDocument: e.data
                }),
                success: successFunc,
                error: errorFunc
            });

            // the controller sends back the merged document
            // that is loaded into the editor
            function successFunc(data, status) {
                TXTextControl.loadDocument(
                    TXTextControl.streamType.InternalUnicodeFormat, data);
                alert("Document has been merged successfully.");
            }

            function errorFunc() {
                alert('Error');
            }
        });
}

Download the sample from GitHub and test it on your own.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • Visual Studio 2012 or better
  • TX Text Control .NET Server (trial sufficient)

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETReportingGitHub

MVC: Adding an Electronic Signature to Documents in Web.TextControl

An MVC sample uses the MailMerge class to populate a signature template with the signer name and image, then inserts it into a named text frame in a contract document. An async controller method…


ASP.NETReportingGitHub

MVC: Loading a Data Source from a View Model

When merging templates with business objects, the Reports ribbon drop-downs in Web.TextControl can be populated from a serialized view model. The controller serializes a class model with the…


ASP.NETReportingMail Merge

MailMerge Class Settings Explained

The MailMerge class provides four properties to control merge output: RemoveEmptyFields, RemoveEmptyLines, RemoveEmptyBlocks, and RemoveEmptyImages. Each property handles unmatched or missing data…


ASP.NETReportingWindows Forms

MailMerge: Conditional Table Cell Colors using Filter Instructions

The TX Text Control MailMerge FieldMerged event exposes TableCell instances during merge for conditional formatting. A CellFilterInstructions class parses filter rules from merge field names and…


ASP.NETReportingWindows Forms

MailMerge: Using Filters to Remove Unwanted Rows

TX Text Control merge block filters remove unwanted rows from repeating data during the mail merge process without modifying the underlying source. Filter conditions applied to merge blocks…

Share on this blog post on: