Implementing Conditional Table Cell Colors with MailMerge
The MailMerge class provides an extensible framework to inject custom logic to the merge process. This ASP.NET MVC sample shows how to implement conditional table cell colors using the online document editor and an ASP.NET backend.

Mail
This enables you to implement features such as conditional table cell colors based on specific filter instructions.
In this sample, the table cell Qty should be highlighted red, if quantity is higher than 10, otherwise it should be green.
This sample shows two interesting aspects:
-
It shows how to use the JavaScript API to store data in the Table
Cell object. - And it illustrates how to merge the created document server-side using Mail
Merge .
The sample implements HTML form elements to set the conditions for table cells. If the input position is inside a table cell, the following code is used to store the conditions in the table cell by serializing the object as a Json string:
// stores the selected conditions in the cell name
function setTableCellConditions(empty = false) {
TXTextControl.tables.getItem(function (table) {
if (table === null)
return; // no table
// create a cellFilterInstructions object
var cellFilterInstructions = {
compareValue: document.getElementById("compareValue").value,
operator: document.getElementById("operator").value,
trueColor: document.getElementById("trueColor").value,
falseColor: document.getElementById("falseColor").value
}
table.cells.getItemAtInputPosition(function (cell) {
if (cell === null)
return; // no cell
if (empty === true)
cell.setName(""); // delete instructions
else
// sel instructions to cell name
cell.setName(JSON.stringify(cellFilterInstructions));
});
})
}
If the input position is changed to another cell, the form elements are updated to reflect the conditions of that cell:
// check cell status on input position changes
TXTextControl.addEventListener("inputPositionChanged", function () {
TXTextControl.tables.getItem(function (table) { // table at input pos?
if (table === null) { // return if no table available
EnableFormElements(
["operator", "compareValue", "trueColor", "falseColor", "enableCondition"],
false); return;
}
// enable form elements
EnableFormElements(
["operator", "compareValue", "trueColor", "falseColor", "enableCondition"],
true);
table.cells.getItemAtInputPosition(function (cell) { // cell at input pos
if (cell == null) { // return if more cells are selected
enableCellConditions(false);
document.getElementById("enableCondition").setAttribute(
"disabled", "disabled");
return;
}
// check the cell name that stores the conditions
cell.getName(function (cellName) {
if (cellName === "") { enableCellConditions(false); return; }
updateSettings(JSON.parse(cellName));
});
});
})
});
Finally, when clicking Merge, the document is saved and sent to the backend controller:
function mergeDocument() {
TXTextControl.saveDocument(TXTextControl.streamType.InternalUnicodeFormat,
function (e) {
var serviceURL = "/Home/MergeDocument";
$.ajax({
type: "POST",
url: serviceURL,
contentType: 'application/json',
data: JSON.stringify({
Document: e.data,
}),
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
TXTextControl.loadDocument(TXTextControl.streamType.InternalUnicodeFormat, data);
}
function errorFunc(error) {
console.log(error);
}
});
}
In the controller, an HttpPost method accepts the document and calls the Merge
[HttpPost]
public string MergeDocument(string Document)
{
using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl())
{
tx.Create();
tx.Load(Convert.FromBase64String(Document),
TXTextControl.BinaryStreamType.InternalUnicodeFormat);
using (TXTextControl.DocumentServer.MailMerge mailMerge =
new TXTextControl.DocumentServer.MailMerge())
{
mailMerge.TextComponent = tx;
mailMerge.FieldMerged += MailMerge_FieldMerged;
string data = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/data.json"));
mailMerge.MergeJsonData(data, false);
}
byte[] results;
tx.Save(out results, TXTextControl.BinaryStreamType.InternalUnicodeFormat);
return Convert.ToBase64String(results);
}
}
The Field
private void MailMerge_FieldMerged(object sender,
TXTextControl.DocumentServer.MailMerge.FieldMergedEventArgs e)
{
// custom field handling
if (e.TableCell == null)
return;
// if TableCell.Name has instructions, create a CellFilterInstructions object
// and evaluate the instructions and set the table cell color
if (e.TableCell.Name != "")
{
CellFilterInstructions instructions =
(CellFilterInstructions)JsonConvert.DeserializeObject(
e.TableCell.Name, typeof(CellFilterInstructions));
// retrieve the color
Color? color = instructions.GetColor(e.MailMergeFieldAdapter.ApplicationField.Text);
// apply the color
if (color != null)
e.TableCell.CellFormat.BackColor = (Color)color;
}
}
Test this on your own by downloading the sample project from our GitHub repository.
Also See
This post references the following in the documentation:
- Javascript: Table
Cell Collection.get Item At Input Position Method - Javascript: TXText
Control.add Event Listener Method - Javascript: TXText
Control.save Document Method
Download and Fork This Sample on GitHub
We proudly host our sample code on github.com/TextControl.
Please fork and contribute.
Requirements for this sample
- Visual Studio 2019
- TX Text Control .NET Server X18 (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.
- Angular
- Blazor
- React
- JavaScript
- ASP.NET MVC, ASP.NET Core, and WebForms
Related Posts
ASP.NETJavaScriptDocument Editor
Detect Toggle Button Changes Using a MutationObserver
This article shows how to detect changes of toggle buttons in the ribbon of the web editor using a MutationObserver. The state of a toggle button in the ribbon visualizes the state of a certain…
ASP.NETASP.NET CoreDocument Editor
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…
Getting Started: ServerTextControl and MailMerge with ASP.NET MVC (.NET…
This article shows how to use the TX Text Control ASP.NET ServerTextControl and MailMerge classes within an ASP.NET web application in Visual Studio 2022.
Deploying the MVC HTML5 Editor to Azure App Services
This article describes how to deploy the ASP.NET MVC HTML5 editor to Azure App Services.
MVC: Loading Files from the Backstage Menu
Happy New Year, everybody! In the last blog entry, we showed how to replace the file menu with an MS Word-style backstage menu. This project shows how to load documents from a partial view in the…