Creating a Razor component using Interop JavaScript integrates and initializes the TX Text Control Document Viewer in Blazor. This sample uses the JSRuntime and DotNetObjectReference classes to communicate between the viewer and the server-side ServerTextControl class in .NET code.
Due to the many changes in .NET 8, applications built with TX Text Control in Blazor require some modifications compared to older .NET versions. Before .NET 8, the entire Blazor application ran in either Blazor WASM or Blazor Server. NET 8 allows you to control the rendering mode by component. This is a big advantage because you can now use the TX Text Control, which requires server-side rendering, with WASM applications.
There are 4 render modes available for .NET 8 components:
- Static server-side
Requests are routed to a Razor Component which returns static HTML. - Interactive Server
Components are more interactive when run through Blazor Server. Interactive DOM modification is dynamic. - Interactive WASM
The component will be executed on the client side (in the browser) and not on the server side. - Interactive Auto
The component uses the Blazor Server for the initial request and then uses the Blazor WASM for subsequent requests.
TX Text Control requires server-side rendering and an update after creation, so this example uses Interactive Server mode.
Data Flow
An illustration of the data flow in this concept is shown in the diagram below. By initializing it with JavaScript, the Text Control Razor component dynamically adds the TX Text Control Document Viewer to the page. The JSRuntime is used to create an object reference to the created JavaScript file. The JavaScript API of the TX Text Control is invoked by this object reference.
Creating the Application
Make sure that you downloaded the latest version of Visual Studio 2022 that comes with the .NET 8 SDK.
-
In Visual Studio 2022, create a new project by choosing Create a new project.
-
Select Blazor Web App as the project template and confirm with Next.
-
Choose a name for your project and confirm with Next.
-
In the next dialog, choose .NET 8 (Long-term support) as the Framework. Select Server as the Interactive render mode and choose Per page/component as the Interactivity location. Confirm with Create.
Adding the NuGet Package
-
In the Solution Explorer, select your created project and choose Manage NuGet Packages... from the Project main menu.
Package Source
Select either Text Control Offline Packages or nuget.org as the Package source. Packages in the official Text Control NuGet profile are frequently updated.
Browse and install the following packages:
- TXTextControl.Web.DocumentViewer
- TXTextControl.TextControl.ASP.SDK
Configure the Application
-
Open the Program.cs file located in the project's root folder.
Before the var app = builder.Build(); entry, insert the following code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersbuilder.Services.AddControllers(); Before the app.Run(); line, insert the following code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersapp.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
Creating the Interop JavaScript
-
Create a new folder scripts in your wwwroot folder, create a new JavaScript file and name it txdocumentviewer.js. Paste the following content into the file you have just created.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersvar dotNetObject; export function loadDocument(document, name) { // load the document back into the editor (TXTextControl) TXDocumentViewer.loadDocument(document, name); };
Creating the Razor Component
This step creates a new Razor component named TXDocumentViewer.razor that initializes both the .NET object reference and the JavaScript object reference.
-
Select the project in the Solution Explorer and choose New Item... from the Project main menu. Select Razor Component, name it TXDocumentViewer.razor and confirm with Add.
-
Paste the following code into the newly created file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters@using Microsoft.AspNetCore.Components.Web @using Microsoft.JSInterop @inject IJSRuntime JsRuntime @inject NavigationManager Navigator <script src="@(BasePath)TextControl/GetResource?Resource=minimized.tx-viewer.min.js"></script> <script src="@(BasePath)TextControl/GetResource?Resource=minimized.tx-viewer-component.min.js"></script> <tx-document-viewer id="viewer1" settings='{"documentData":"VGV4dCBDb250cm9s", "dock":1, "basePath":"@(BasePath?.TrimEnd('/'))"}'> </tx-document-viewer> @code { [Parameter] public string? BasePath { get; set; } private DotNetObjectReference<TXDocumentViewer> DotNetReference => DotNetObjectReference.Create(this); private IJSObjectReference? _txdocumentviewer; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { _txdocumentviewer = await JsRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/txdocumentviewer.js"); } } [JSInvokable("LoadDocumentFromFile")] public void LoadDocumentFromFile(string filename) { // check if the file exists if (!System.IO.File.Exists(filename)) { return; } // load the file into a byte array byte[] bDocument = System.IO.File.ReadAllBytes(filename); // invoke the JS function 'loadDocument' to load back to the modified document _txdocumentviewer?.InvokeVoidAsync("loadDocument", new object[] { Convert.ToBase64String(bDocument), filename }); } }
Any function of the referenced txdocumentviewer.js JavaScript file can be called using the created IJSObjectReference _txdocumentviewer. The DotNetObjectReference<TXDocumentViewer> points to this Razor component. This is passed to the JavaScript functions to save and reload the document.
Consuming the TXDocumentViewer Razor Component
In this step, we are going to use the Razor component we have created on a page.
-
Find the Home.razor page in the Pages folder and replace the content with the following code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters@page "/" @rendermode InteractiveServer @inject NavigationManager Navigator; <div style="width: 800px; height: 600px;"> <TXDocumentViewer BasePath=@Navigator.BaseUri @ref="_txdocumentviewer"> </TXDocumentViewer> </div> <button @onclick="LoadDocment">Load Document</button> @code { private TXDocumentViewer? _txdocumentviewer; // insert a table using the client-side API private void LoadDocment() { _txdocumentviewer?.LoadDocumentFromFile("App_Data/demo.tx"); } } -
Select the project in the Solution Explorer and choose New Folder from the Project main menu. Name it App_Data and copy the following file into it:
In the Solution Explorer, set the Copy to Output Directory property to Copy always.
Compile and start the application.
Button: Loading a Document
The LoadDocument() method is called in the .NET code of Home.razor when the button is clicked.
private void LoadDocment() | |
{ | |
_txdocumentviewer?.LoadDocumentFromFile("App_Data/demo.tx"); | |
} |
This calls the LoadDocumentFromFile() method of the TXDocumentViewer.Razor component where a server-side file is loaded into a byte array.
[JSInvokable("LoadDocumentFromFile")] | |
public void LoadDocumentFromFile(string filename) | |
{ | |
// check if the file exists | |
if (!System.IO.File.Exists(filename)) | |
{ | |
return; | |
} | |
// load the file into a byte array | |
byte[] bDocument = System.IO.File.ReadAllBytes(filename); | |
// invoke the JS function 'loadDocument' to load back to the modified document | |
_txdocumentviewer?.InvokeVoidAsync("loadDocument", new object[] { Convert.ToBase64String(bDocument), filename }); | |
} |
This calls the JavaScript function loadDocument() in the txdocumentviewer.js JavaScript file:
export function loadDocument(document, name) { | |
// load the document back into the editor (TXTextControl) | |
TXDocumentViewer.loadDocument(document, name); | |
}; |
For your own testing, you can download and try this sample from our GitHub repository.