Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Explore Blazor WebAssembly - use custom style, call external WebAPI, employ JavaScript interoperability

15 Apr 2020 2  
This article will demo the usage of Blazor WebAssembly and how to create simple web application with it.
The article consists of three parts. In Part 1, we will work with styles. In Part 2, we will call external webAPIs. In Part 3, we will work with JavaScript interoperability.

Motivation

Blazor is a framework from Microsoft® for making web applications with .NET. In very short, Blazor is C# for web browsers. There are two types of Blazor, Blazor WebAssembly and Blazor Server. This article is about Blazor WebAssembly. Notice that during the writing of this article, Blazor WebAssembly is still in preview. The term WebAssembly refers to a binary instruction format for stack-based virtual machine. In short, it makes C/C++, Rust, C#* run in a web browser. It is designed to run alongside JavaScript. WebAssembly is an open web standard and it is supported in (most) web browsers. Those browsers who support it, all major browsers, supports it without plugins.

This article will demo the usage of Blazor WebAssembly and how to create a simple web application with it. The article consists of three parts.

In Part 1, we are going to remove the default CSS framework and use other CSS framework, w3.css. Not because the default CSS is bad, it is more like to make styling simpler and show how easy it is to change it.

In Part 2, our web application will display dummy data from an external source, in this particular case, an IBM Cloudant database. IBM Cloud allows users to develop for free, to build for free on IBM Cloud. No credit card is required for creating the account, as opposed to other providers, which require a credit card even for free accounts. I guess this will allow a wider audience to follow the article. The performance of free account is same as the paid one. Of course, the free account comes with restrictions – one of them is the cap of number of available calls to the cloud DB. For a production application, you will need a paid account with a plan tuned to your needs.

In Part 3, our demo web application will use C# and JavaScript together, technically known as JavaScript interoperability. It will be working with Airbnb® Lottie animation library. Grace to Lottie, our web application will display exciting svg animations. Lottie animations are usually done with a paid product, called Adobe® After Effects. We are going to use few already created animations, released by their authors for free.

Table of Contents

What You Will Be Able to Make if You Follow the Entire Article

The entire solution is created from scratch. It will require some typing and some work. If there is a place, where you give up reading it and move to another reading, then this one is the best. This article will not explain the code line by line, you need to read the code itself and figure it out. Of course, if there are questions, I will try to answer them to my best knowledge. In animated gif below, you can see the finished web application and its usage. Credits to the artist who made his Lottie animations available for free, you can find a link below in the article, when the part for using Lottie animations with JavaScript interoperability is explained in details. And of course, thanks to all who made their tools and systems available for free and this way allow people to create freely. Not only the tools mentioned in the prerequisites, but also Libre Office which provides the editor for typing the article during the creation, Screen to Gif for providing the tool for making the animated gif and many more.

Image 1

Prerequisites to Follow this Article and Make the Described Solution

This solution was created in spring of 2020 (amidst the Corona Covid-19 times), so current versions, at this time, of all products and corresponding frameworks, NuGet or NPM packages were used. For the .NET solution, the following IDE was used:

  • Microsoft Visual Studio Community 2019, available as a free download from MSDN. Notice that because this is a .NET core project, you can create it with .NET Core CLI and use any other editor. It should be possible to create the project under any other OS (Linux, macOS), as long as they are supported by .NET Core.

You need to install Blazor WebAssembly template. In order to have it, you will need the .NET Core 3.1 release as well. I have used the SDK release.

  • .NET Core 3.1
  • Blazor WebAssembly template

An IBM Cloud account. You can create a developer account for free, no credit card required, on IBM Cloud and use lite plan services:

  • IBM Cloudant

the following clide side JavaScript framework:

  • lottie.min.js

and the following CSS framework

  • w3.css

Optional - for making a simple local WebAPI, in order to be called by our Blazor web application:

  • Visual Studio Code, available as a free download from MSDN
  • node.js, available as a free download from node.js website
  • express NPM package

"Oxanium" font was used as the default font.

Part 1 - Get Started

In this part, we are going to create the Blazor WebAssembly solution. If you don’t have .NET Core 3.1. SDK, then you should follow the instructions provided by Microsoft and install it. You can use the certutil tool, installed with Windows, to verify the sha512 hash. Or some other tool.

Image 2

Then, we continue with the main stuff for this part:

  • We open the Developer Command Prompt for Visual Studio 2019. We type
    dotnet --version
  • If all is good and we see the version number, we continue forward.
  • We type the following command:

    dotnet new -install Microsoft.AspNetCore.Components.WebAssembly.
    Templates::3.2.0-preview02.20160.5

    Then, we get this error message:

    Image 3

    You know, it is either -i or --install, you cannot just type something install something. NPM, what is this npm install express, where are the -'s and --s? It look like a human readable sentence line that, it is so easy to use :)

  • It might be a good thing to see the recent documentation, provided by Microsoft for exact string for typing the command for installing the Blazor WebAssembly template. In our case, the recent string is as follows:

    dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview2.20160.5

    You can then verify that the WebAssembly template is installed:

    Image 4

  • Then we start Visual Studio 2019 and we click on Create a new project.
  • From the Create a new project window, we select Blazor App and click on Next.
  • In Configure your new project window, we specify the name of the project, location and solution name. I have chosen the name BlazorFirstSteps, and as location, I choose D:\devdemos\ on my machine (the drive and folder were existing before).
  • We confirm with Create.
  • The Create a new Blazor app window appears. The Blazor WebAssembly application project template is shown, as we installed it few steps above. We select it.
  • We also check ASP.NET Core hosted (Nor that it matters precisely for this article, as we call external WebAPIs).
  • We confirm with Create.

Image 5

A few moments later, our solution is ready. We select Debug -> Start Debugging or press F5 or click on the debug button in Visual Studio toolbar. If all is good, the default Blazor template appears in our browser of choice. In Part 1, we are going to use Brave browser. We click on Fetch data and on Counter and test them, just to see everything is working. Pay attention that even that we use Debug, it is not actually (yet) possible to debug the C# in blazor @code part. Later in this article, we are going to use Start without Debugging. It is kind of a personal choice at the end.

Image 6

Changing the CSS Framework and Removal of Some Stuff We Are Not Going to Use

  • We select Debug->Stop debugging or press Shift+F5 or we click on the (corresponding) button in Visual Studio toolbar.
  • We download w3.css from w3schools website. Any other CSS framework will be OK to use, we are going to use w3.css because it is fairly simple and easy to use, and it is explained very well by its authors. I save it in D:\devdemos\BlazorFirstSteps\BlazorFirstSteps\Client\wwwroot\css.
  • I also create a folder D:\devdemos\BlazorFirstSteps\BlazorFirstSteps\Client\wwwroot\css\fonts. Then, I go to Google Fonts webpage and from there, I download a font. Oxanium in this case. I save the OFL.txt and Oxanium-Regular.ttf from the downloaded compressed archive to the newly created fonts folder.

Now comes the fun part, where we delete some stuff:

  • Within Visual Studio solution explorer, we delete the following BlazorFirstStep.Client project folders: wwwroot/css/bootstrap and wwwroot/css/open-iconic, as well as wwwroot/css/site.css file.
  • Then, we delete the Counter.razor and FetchData.razor files from the Pages folder.
  • Then, we delete SurveyPrompt.razor from Shared folder.
  • In BlazorFirstSteps.Server project, we delete the WeatherForecastController.cs file from Controllers folder.
  • In BlazorFirstSteps.Shared project, we delete WeatherForecast.cs file.

It might be a good idea to remove unused usings for every C# file, which you are going to use.

Making the New Layout

Then we are going to change the main markup file, index.html, and to tune up the navigation, so it works after changes we have made so far.

  • We open the index.html file and remove the references to the former CSS files. Then, we update the references so that they point to new files.
  • Inside body tag, we change the <app>Loading...</app> to <iputherewhatiwant>Loading...</iputherewhatiwant>
  • Optional - I have specified the usage of the font, which I have downloaded few steps earlier. Here is how index.html looks now:Image 7
  • We simplify the navigation in NavMenu.razor. We will make the styling even simpler, by removing the usage of NavLink's and all of the code-behind. It looks like this now:Image 8
  • We remove some markup from Index.razor as well. Here is its final look for part one:Image 9
  • and we specify in program.cs the starting tag for our Blazor WebAssembly app, the tag which we have changed earlier. If you decided to leave it as it was, no changes are required here as well. We will not change this file further for the entire article.Image 10
  • Finally, we simplify the layout of entire web application, changing the MainLayout.razor. We simply have a NavMenu above and below is the content. Here is the final look:Image 11
  • Optional - I went to w3.css file and I manually specified 'Oxanium' for body and header parts, removing the default fonts. I have changed the values and units for font size for h1 till h6 as follows: 3.6 vw, 2.6vw, 2.0vw, 1.4vw, 1.0vw, 0.9vw and for body, I see 0.8vw.

At this point, again, we run the application. This is how it looks now:

Image 12

We are almost ready with the first part. It remains to add two pages in Pages folder, one for live demo and other for working and to update the NavMenu, so that we are able to navigate those two pages.

  • We select Pages folder and right click on it. From context menu, we select Add -> New Item and then Razor component
  • We name it LiveDemo (LiveDemo.razor)
  • We do similar steps and create another one, called Working (Working.razor)
  • In LiveDemo.razor, we add the @page "/livedemo" at the very beginning of the page and for working, we add @page "/working
  • We made the final update of NavMenu.razor in Shared folder. Just adding navigation to the newly created pages. Till the end of the article, this file is not going to be changed. Here is it:Image 13
  • And here is the final look of our Blazor WebAssembly web application for the first part. I have added the code for working.razor in front of it, just to make better demonstration. Now it is time for making web calls, dealing with CORS and more fun. Time for part 2.Image 14

Part 2 - Working with WebAPIs - Calling IBM Cloudant, POST and GET, and Few Words about _id

This part assumes successful completion of Part 1 or a working application similar to it. A common feature in a web application is making calls to remote APIs via the http protocol. At this point, many other tutorials assume that the remote API is existing or they suggest usage of an existing demo API. In this article however, we do everything ourselves. This part of the article is again divided into two - the first, an optional part, where we create local simple service via node.js and express and we pretend it is our web API, and the second part, which is going to be needed further in the article, where we call IBM Cloudant database. We are going to demonstrate how to set up the database and how to use it for doing basic stuff in our Blazor WebAssembly web application.

Optional - Making Local node.js Hosted Server

The default Blazor WebAssembly template comes with a server project and a demo controller, as well as demo class in Shared project. The calling of those is straightforward, Visual Studio even provides you with default implementation of C# methods for making calls via four main HTTP methods, GET, POST, PUT, DELETE, to REST web API, via its scaffolding option. When we run the default template, we see that this is working just fine. The Server and Client in this case both share the same domain, localhost:44312 in my particular case. Let’s explore what will happen when we call other service, hosted on another domain.

I have created a folder D:\devdemos\BlazorFirstSteps\nodejsdemo. We open a Node.js command prompt and we navigate to our working folder. If you create it in a different location, you should navigate accordingly. We type:

npm install express

It confirms that the installation is OK and warns about few things. We can create the REST, only the GET part actually, without express, but I guess it is a little bit easier the way I present it here.

Image 15

Then, we open Visual Studio Code, then we open the folder we just created. We create a new file called demodata.json. The content of the file is as follows:

Image 16

Now we create a server.js. Bear in mind that we are going to slightly change it few steps below, so that here is the initial version. We are going to run it via our node.js command prompt. You can run it as well with Windows® PowerShell. Visual Studio Code support terminal integration with PowerShell, so it is possible to run commands inside editor as well, like this:

Image 17

In this tutorial, we will keep things simple and use the command prompt. So, we type...

node server.js

...in our command prompt and get the server running.

Image 18

Then, we navigate to localhost:3030. We can see the demo.json content, which we created few steps earlier.

Image 19

We go back to Visual Studio solution and open working.razor. We are going to make a GET call towards localhost:3030. We are going to use HttpClient, provided by Blazor. The code for Working.razor for this part is as follows:

Image 20

and now we run our Blazor WebAssembly web application (for Part 2, I have changed the browser to Microsoft Edge Beta, which again Chromium based), and to Working. Then, we click on the button. Nothing happens, not even a message with response status string, different than OK, is shown.

Image 21

Nothing is shown, because the browser itself has blocked the call. Let's open the developer console tab of our browser and see the error there. Main thing is the following: Access to fetch at 'http://localhost:3030/' from origin 'https://localhost:44312' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Any Chromium based browser will display the same error. Mozilla's Gecko, (still) used in Firefox, will describe the error as: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'http://localhost:3030/'. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

So in short, our browser asked the server about CORS and did not like what the server told it. And because of that answer, the browser blocked the call. So, while our Visual Studio solution is running, we go back to node.js command prompt and stop the local server. Then, we change the server.js by adding few lines about CORS. Here is the final look:

Image 22

and then we start the node.js server again. During our small manipulation, our Blazor web application was still running, we did not switch it off. Let's go back to our browser and click the button again.

Image 23

Good work! We get our demo data shown. Data is the same, the type I have made when making the json is here as well. :) And now, let's move forward.

Working with IBM Cloudant Database and Using It with our Blazor WebAssembly Web Application

You will need an account for IBM Cloud in order to follow, as stated in prerequisites. As of the time of writing this article, you can create a developer account for free, no credit card is required, as opposed to some other major providers. I am not going to explain the steps in detail here, because the IBM Cloud is a commercial site, owned by IBM, and they can change the way it is working according their needs, meaning any detailed description can be made obsolete.

IBM Cloudant

IBM Cloudant is a NoSQL cloud database, provided by IBM. When you log in into IBM Cloud and go to Catalog and then select Databases, you will see something like this, depending on your plan. There was filter for Lite plan selected, when the screenshot was made. So, you can follow the instructions and create a Cloudant database from here. There are some things to specify - locations, plans, etc., which you have to decide on your own.

Image 24

After you create the Cloudant database, you can see an overview of it. You can manage it, manage Service Credentials, Plans and Connections.

Image 25

You will need to create a service credentials. After you create those service credentials, you will be able to call your database using some of them. We are going to use Basic Authentication, so we will need the username and the password.

Image 26

Now, it is time to launch the Cloudant Dashboard. You might notice that you are redirected to a new URL, having your (IBM Cloudant) username in it. We will refer to this part of site simply as Dashboard. From Dashboard, you select Databases and then you click on Create Database. I choose the name exploringblazor, as only lowercase characters are allowed, I have specified the options and I have confirmed with Create.

Image 27

We need objects to store our data. So we have to design, or following Cloudant terms, to create a document. We click on Create Document or we click on the + sign in Design Documents and we select New Doc. A default document appears, having an autogenerated identification key (_id). In this document, we are going to add few more fields. This is how the document looks just before we save it.

Image 28

After we save it, we can look at it by going to All Documents and from there by selecting it. If we look at it in greater detail, we can see that Cloudant had added a revision value (_rev). Using this revision, Cloudant will track changes of document. There is a button called {} JSON. If you are looking at a document via the Dashboard editor and click on it, it will display the document, a json file, in a browser. Let's do that. We are going to need the URL displayed in the browser. First part of this URL is your username, then comes the database name, and then comes either a document id, or kind of query or something else. :)

Image 29

One final thing before we start populating fake data. We need to enable CORS for our newly created database. So from Dashboard, we go to Account -> CORS. You might need to enable CORS. Later, we type the domain we need, in my case localhost:44312. By default, unauthenticated connections are rejected by Cloudant, so we can put that localhost:port stuff. On later point, I will remove it, probably once I am ready with the making of this article.

Image 30

Fill Some Dummy Data Using Our Web Application

We have created a document using Dashboard UI and looked at it. Usually databases contain millions, and even more, records or documents. We have to add more documents to our database, even for a simple demo. The good news is that we already have a working web application and we can use it for doing just this. How cool is that! :)

When working with Cloudant and you POST data, usually in bulk, you must not provide a duplicate _id. So, if you have an class in your C# solution, you have to play with this _id property - it should not be serialized when json is made, but it should be deserialized, because you will need to identify a document if you want to track it, change it, etc. At the moment of writing this article, System.Text.Json does not support that out of the box, you have to write custom code for it (contrary to Newtonsoft.Json for example). Anyway, in our sample, this advanced usage will be omitted and we will simply not deal with _id and _rev in our Person class, the class we are going to create to handle the data in Cloudant.

I am going to generate some dummy data using simple class. Usage of faker/bogus data generators is a good thing, but in our case, they will be slow and for our simple application, there is no need for them now. More, I will create two enums, one for Status and one for Location, and the Person class.

  • Here is the Location enum:

    Image 31

  • and here is the Status enum:

    Image 32

  • This one is the Person class, which will be mapped to the json data in Cloudant. Cloudant is a document database, so in it any document can be added, it is not needed to follow the structure we created above or this one. This class is simply for convenience.

    Image 33

  • and here is the class I am going to use so that dummy/fake data are generated. It will be placed in Client project, not in Shared, as the previous three files.

    Image 34

  • and now, we are ready to again modify the Working.razor file. The markup and code will be more complicated this time, but not so much. As stated earlier, we are going to need the username and password, required for authentication, and the endpoint, prepared for our Cloudant database. By the way in (bl/r)azor file, you can see how to call a method with an argument and how to call it without, amongst other things. Pay attention to StateHasChanged call in one method, and the lack of its call in another method. Both methods are updating the UI. And pay attention to [Parameter] attribute, sometimes it is needed, sometimes is not and just makes the code encumbered. I have not always remove it, as it will become obvious in some of the following screenshots:

    Image 35

If you are good with changes so far, it is time for running the web application and generate some fake data. We navigate to Working page and click on buttons to generate some number of records. Then we save them to Cloudant. We might do this several times. The process is split on separate generation and call to database in order to see how long each one of those processes is taking. For example, if you have a slow fake data generator, you should see it immediately when generating the data, not when you save it. In our case, both processes should be quite fast. Here is the screenshot made just before I click the Save to DB button for the first time.

Image 36

and if everything goes well, we should see the created data in our Cloudant database. Those points are important, so play some time here, make sure everything is working, before moving forward.

Image 37

I will create more records, to increase their number and work with slightly more data. Animated gif in the beginning was made while there were between 15-20 000 records in database. We are close to the end of Part 2, now we have just to get data from Cloudant.

Execute a Query Against Cloudant Database and Show Raw Result in Our Web Application

The other (bl/r)azor page, LiveDemo.razor, will serve this purpose, for the sake of demonstration. We can show the usage of classical code-behind classes in Blazor.

  • We create a class called LiveDemo (file can be LiveDemo.cs) in the Pages folder. The class will have a partial modifier, so that it works with existing markup of LiveDemo.razor.
  • We do not need @code in LiveDemo.razor anymore, so we remove it. We keep only a heading and one text input, where we can type characters and query the cloud database. We bind the content of entered text to a string property, update the property on every input, grace to oninput binding, and we call the MakeQuery method on every key press.

    Image 38

  • In LiveDemo class, we create the HttpClient as private variable, we do not inject it as we did in Working.razor. The code is similar to code in Working.razor, we make a call to an endpoint, we authenticate our call, and this time we GET results, we do not post them. And there is some character handling on key press, we make the call to cloud database only when Enter is pressed.

    Because Cloudant is a NoSQL database, we cannot use SQL for making queries. You can consult the official documentation for getting more information on how to make queries against and the details involved there, as well as numerous articles around the web. This article is about Blazor, I place all those details about Cloudant in order that every reader, acknowledged with Cloudant or not, is able to follow the steps. So in short, we keep the queries and all other stuff very simple.

    I will try to explain what I am making the query do. For example, for all of the records I have generated and saved, I would like to have only those, having last name starting with "Tho", like Thomas or Thompson. This is the query for this, executed in Dashboard:

    Image 39

    We can limit the number of records returned, we can sort them, we can optimize the query execution, and we can do so many other things. For our application, we will query the last name when at least 3 characters are typed. Finally, here is the LiveDemo.cs:

    Image 40

  • We can run now our web application and navigate to Live demo page. There, we can type some search string and confirm with Enter. Let's type "Smi" and confirm (Cloudant is case sensitive, so if we type "smi", we will get a different result).

    Image 41

Cool, we have the records from Cloudant. We are ready with Part 2! Good job! For now, our application just shows raw json, resulting from our call to cloud database. We are going to change the way it looks in the next part and we are going to add some animations for making it look even cooler.

Part 3 and Final - JavaScript Interoperability

JavaScript is de facto the standard language for the web. It is the most popular language on github, it is the term people ask most on stackoverflow (followed by Java, C#, Python and PHP). Blazor WebAssembly web applications can call (invoke is the precise term used in Blazor documentation) JavaScript functions and .NET methods can be called by JavaScript functions. This functionality is know as JavaScript interoperability, sometimes shortened to JS interop.

Basic Example

JavaScript interoperability in Blazor is explained well in its documentation, blogs etc., so you can omit this part. We are going to demonstrate the idea, because in following slightly more complicated examples, we need this working properly. In our C#, we are going to use an interface called IJSRuntime. We are going to create a JavaScript function, which we will place in index.html, and we are going to call it in Home page or Index.razor. Here is the index.html after our changes:

Image 42

and here is the index.razor:

Image 43

It remains to show the Home page, screenshot is made after I have clicked twenty times on the button. :) For the third part of the article, I am using Opera browser.

Image 44

AirBnB Lottie Animations

Lottie is the name of a library, that renders Adobe After Effects animations in real time, allowing applications to use animations as easily as they use static images. In HTML, those animations are finally made into SVG animations, when the final markup is made in client browser. We want this in our Blazor WebAssembly web application. Instead of images, we want to show animations. There are some web pages, where artists are generous enough and share some of their work. I am going to use few animations made by this artist - you can find his details on the following link, 'https://lottiefiles.com/Dahish'. It is from this site that I have downloaded the Lottie animations, used in the article, you can find plenty of Lottie animations there. Thanks for the good work and for sharing. I am going to save two of those animations in D:\devdemos\BlazorFirstSteps\BlazorFirstSteps\Client\wwwroot\css\jsons and name them good.json and bad.json.

Next, we are going to get the lottie.min.js from cdnjs site. I have used the following link: 'https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.6.7/lottie.min.js'. I have saved the file in D:\devdemos\BlazorFirstSteps\BlazorFirstSteps\Client\wwwroot\scripts under the name lottie.min.js. And later, I have created a file called workLottie.js in the same folder. The content of this file are as follows (I have put an interesting command in file itself, as a reminder mainly to myself about few troubles I experienced when playing with this):

Image 45

Now we have to update Index.html and include references to both scripts, lottie.min.js and workLottie.js. If you did the optional part above, you have to remove the script method used there, if you want the final look of the file to be like this:

Image 46

This will be the final version of index.html for the article. We continue by updating Index.razor, so that we load one of our animations and just check that everything is working fine so far. In order to display more animations at once, we are going to use Blazor components. This will be explained further in the following paragraphs. Back to Index.razor, Lottie animations, which in the final HTML, served at the client, will be svg animations, will be referred via ElementReference. Pay extra attention when working with external JavaScript libraries and you invoke them in Blazor, especially if they deal with rendering of elements. Here is the final version of Index.razor, the one seen in action in the animated gif as well:

Image 47

and this is the Home page in the browser:

Image 48

Formatting JSON Data, Received From Cloudant, as HTML and Using Blazor Components for Displaying Lottie

We have come to the final part of the article. First, we are going to make a special component, so that we display multiple Lottie animations on a page with (relative) ease. We will get then only the docs part from all json data, provided by Cloudant, other part being bookmark and warning if any, see Part 2 of the article for more details, and convert those documents to an array of Person objects. We will display properties of those Persons and we will format the HTML markup even further by using the Lottie animations.

Making of a Blazor Component

Nothing fancy here, components are common for Blazor. We want to confine all the logic for working with Lottie in one C# file and just use this component as an image - that will say we say the name/path of the animation and we will expect corresponding animation to be shown in our page. We can use this component directly in our LiveDemo page. However, in it, in Live demo page we intend to display also multiple person and their fake generated data, so not only an animation for every person, but also names, location, and a number. Depending on the status, good or bad, we should display different animations, one for good and another for bad (and none for neutral, maybe just some strings to emphasis the difference). The markup for all this will not be trivial, so it will be a good idea to contain it in a component as well. So, first, we create a component for the animation only:

  • We create a folder called Components in our BlazorFirstSteps.Client project
  • We select the folder and Add -> New Item -> Razor Component called LottieComponent.razor

    Image 49

  • We change its contents to following ([Parameter] for the Lottie path property is a must):

    Image 50

    We call the method for displaying the element in OnInitialized method. I would suggest to experiment and try to call this method in this way in OnAfterRender or its async counterpart, or some of the other methods, called after a page loads, and observe whether there can be some unexpected behaviours. Especially with OnAfterRender, which is called twice when a page is rendered.

Now we will create a component, markup only, for displaying a single person. The markup will be quite simple, kind of card or a tile, some strings displayed in one column, some other strings displayed below, same thing in next column and then the animation. We will not get into big UI details, for example what will happen when some of those strings are too long :). Having tile, card or component like that will allows us easily to display multiple of it on one row in Live demo page.

  • We select the folder and Add -> New Item -> Razor Component called PersonComponent.razor.
  • We will need some logic to determine which animation is to be shown in which case and the other is markup. All will be in razor file, no partial classes. Here is how it looks, [Parameter] here for the property is a must:

    Image 51

Parsing Documents From the Received JSON to an Array of Objects

For easier work, we will create class for parsing the raw json response, received from Cloudant. We will call it Cloudant. It is quite simple and matches the defined structure by the cloud database. When we put the data in Cloudant, we have used anonymous class, this is another approach too. Here is it, Cloudant.cs:

Image 52

We are almost ready, only two things remain, the code-behind and markup for Live data page. In LiveData.cs, we will have an array of Persons, which are going to be shown. We will fill this array by copying data from docs property of newly created Cloudant object. The rest is similar to code for LiveData.razor in Part 2.

Image 53

The markup for LiveDemo.razor is pretty simple, especially as we put most of the necessary stuff in Person and Lottie components. We want the results shown in three columns, so we have a simple code for doing so. And here it is, the final markup for the article:

Image 54

It was a long journey, but now we are ready and we can enjoy. We can run the demo Blazor WebAssembly web application and go to Live Demo, type something and see properly formatted results with animations displayed for those records, which meet certain conditions. Like this:

Image 55

If you followed up to now, you will probably have a similar application and you can run stuff, close to those, demonstrated by the gif animation at the beginning of this article. Good job!

I Hope You Enjoyed the Article

I have tried to create a good educational article, with emphasis on a few important points. I have tried to fix all typos - code, functional or syntax, and I hope there are none, which are considerable. I hope someone finds this article interesting.

History

  • 13th April, 2020: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here