Merging Templates with MailMerge with Different Merge Field Settings in C#
This article shows how to merge templates with different merge field settings using the MailMerge class. The various settings allow for the removal of unused fields or the possibility to make changes to fields after the merge process.

When providing users with the ability to modify documents after they have been generated by Mail
Merge Data
Consider the following scenario where a particular JSON data source is being used for template creation.
[
{
"id": 1,
"customer": {
"id": 1,
"name": "John Doe",
"street": "123 Main St",
"city": "Anytown",
"state": "TX",
"zip": "12345"
},
"items": [
{
"id": 1,
"name": "Widget",
"price": 9.99,
"quantity": 2
},
{
"id": 2,
"name": "Thing",
"price": 5.99,
"quantity": 5
},
{
"id": 3,
"name": "Gadget",
"price": 199.99,
"quantity": 1
}
],
"total": 0
},
{
"id": 2,
"customer": {
...
The controller loads this JSON and passes it to the view, where it is loaded into the editor to populate the dropdowns with the correct merge field names.
public IActionResult Index()
{
string json = System.IO.File.ReadAllText("App_Data/data.json");
ViewBag.Data = json;
return View();
}
Sending Data to Endpoint
The view code loads the JSON and makes a jquery AJAX call to send the create template to the Merge endpoint.
@using TXTextControl.Web.MVC
@Html.TXTextControl().TextControl().LoadDataFromJson(ViewBag.Data).Render()
<input type="button" onclick="mergeDocument()" value="Merge Document" />
@section Scripts {
<script>
function mergeDocument() {
TXTextControl.saveDocument(TXTextControl.StreamType.InternalUnicodeFormat, function (results) {
$.ajax({
url: '@Url.Action("Merge")',
type: 'POST',
contentType: "application/json",
data: JSON.stringify(results),
success: function (data) {
TXTextControl.loadDocument(TXTextControl.StreamType.InternalUnicodeFormat, data);
}
});
});
}
</script>
}
The editor enables users to create the template by adding available merge fields and merge blocks.
After the merge process, the returned document contains merged content and the field functionality is removed.
Preserve Empty Fields
Now consider that there are fields in the template that have no data. By default, these fields are removed after the merge.
The following screenshot shows the merged document with the empty "MERGEFIELD" field removed.
By setting the Remove
using (MailMerge mm = new MailMerge())
{
mm.TextComponent = tx;
mm.RemoveEmptyFields = false;
// load json data
string json = System.IO.File.ReadAllText("App_Data/data.json");
// merge data
mm.MergeJsonData(json, true);
}
Learn More
The MailMerge class provides several settings to control the merge process and formatting in the resulting document. There are several switches to control how text fields, blocks, images, and blank lines are handled. This article provides an overview of when and how to use each option.
Preserve Field Functionality
But now consider a scenario in which you want the merged fields to be editable after the merge process is complete. In this case, there is not a property that is available, but there is a typical workflow that allows this to be realized. Each field provides an event that fires when fields are merged. It is usually used to change the contents of the field after the merge.
The advantage of this process is that the functionality of the field is maintained after the field is changed.
The following code attaches the event to the MailMerge object, passing the merged content back to the field.
[HttpPost]
public IActionResult Merge([FromBody] Content results)
{
using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl())
{
tx.Create();
tx.Load(Convert.FromBase64String(results.Data), TXTextControl.BinaryStreamType.InternalUnicodeFormat);
using (MailMerge mm = new MailMerge())
{
mm.TextComponent = tx;
mm.FieldMerged += Mm_FieldMerged;
// load json data
string json = System.IO.File.ReadAllText("App_Data/data.json");
// merge data
mm.MergeJsonData(json, true);
}
tx.Save(out byte[] data, TXTextControl.BinaryStreamType.InternalUnicodeFormat);
return Ok(Convert.ToBase64String(data));
}
}
private void Mm_FieldMerged(object sender, MailMerge.FieldMergedEventArgs e)
{
e.MergedField = e.MergedField;
}
As a result, the merge fields are populated, but the field functionality remains intact.
This allows users to modify these fields and other content and merge the template again Another use case is previewing live data during the template creation process without losing field functionality.
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.
- Angular
- Blazor
- React
- JavaScript
- ASP.NET MVC, ASP.NET Core, and WebForms
Related Posts
ASP.NETASP.NET CoreDocument Editor
Getting Started Video Tutorial: Document Editor in ASP.NET Core C# on Linux
This video tutorial shows how to use the Document Editor in an ASP.NET Core application using C# and deploy on Linux using Docker. This tutorial is part of the TX Text Control Getting Started…
Use MailMerge in .NET on Linux to Generate Pixel-Perfect PDFs from DOCX…
This article explores how to use the TX Text Control MailMerge feature in .NET applications on Linux to generate pixel-perfect PDFs from DOCX templates. This powerful combination enables…
Generating Dynamic NDAs Using TX Text Control MailMerge in C# .NET
This article demonstrates how to generate dynamic NDAs using TX Text Control MailMerge in C# .NET. It covers the process of creating a template, binding data, and generating the final document.
Designing a Maintainable PDF Generation Web API in ASP.NET Core (Linux) C#…
This article shows how to create a PDF generation Web API in ASP.NET Core on Linux using TX Text Control .NET Server. The clean architecture is used to create a maintainable and testable solution.
ASP.NETApp ServicesASP.NET Core
Deploying the TX Text Control Document Editor in an ASP.NET Core Web App to…
This tutorial shows how to deploy the TX Text Control Document Editor to Azure App Services using an ASP.NET Core Web App. The Document Editor is a powerful word processing component that can be…