How To Render Avatar Images From XML Data In Blazor?

Introduction

In the world of web development, making websites that people find easy to use and fun to interact with is super important. One cool thing you can do to make your website more interesting is to show pictures of people (avatars) in little pop-up windows when someone clicks or hovers their mouse over something, like a user's profile or a comment. It not only makes your website look better but also helps users learn more about things quickly. In this article, we'll learn how to put avatar pictures into pop-up windows using XML data. We ll use HTML, CSS, and C# to do this.

What is Blazor?

Blazor is an open-source web framework developed by Microsoft that allows developers to build interactive web applications using C# and .NET instead of JavaScript. Blazor enables full-stack web development with a single programming language and runtime.

There are two primary hosting models for Blazor.

Blazor WebAssembly

This model allows you to run Blazor applications directly in the web browser using WebAssembly, a technology that enables executing code written in languages like C# in the browser. Blazor WebAssembly applications are client-side and can work offline once loaded.

Blazor Server

In this model, the application's user interface (UI) is rendered on the server, and the UI updates are sent to the client (web browser) over a SignalR connection. Blazor Server applications maintain a persistent connection to the server, allowing for real-time interactivity.

Prerequisites

Before we get started, make sure you have the following prerequisites.

  • Visual Studio or Visual Studio Code installed.
  • Basic knowledge of C# and Blazor.

Step 1. Create a Blazor Server Project

Let's start by creating a new Blazor Server application. Open Visual Studio or Visual Studio Code, and create a new Blazor Server project.

After creating a Blazor Server project, you will have this type of project structure.

blazor  server project

When you run this default project, you will see a certain type of interface.

default project

Step 2. Create XML Data

We will create a simple XML file to store avatar data. First, create a folder named 'app_data' in the project's root directory. Inside this folder, create a file named 'avatars.xml.'

<?xml version="1.0" encoding="utf-8" ?>
<Avtars>
	<Avtar>
		<AvtarId>1</AvtarId>
		<AvtarName>basketball-boy</AvtarName>
		<AvtarUrl>images/Avatar/bird150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>2</AvtarId>
		<AvtarName>boy-scout</AvtarName>
		<AvtarUrl>images/Avatar/cat150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>3</AvtarId>
		<AvtarName>ballerina-girl</AvtarName>
		<AvtarUrl>images/Avatar/dog150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>4</AvtarId>
		<AvtarName>girl-with-braid</AvtarName>
		<AvtarUrl>images/Avatar/elephant150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>5</AvtarId>
		<AvtarName>tomboy</AvtarName>
		<AvtarUrl>images/Avatar/frog150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>6</AvtarId>
		<AvtarName>backpack-boy</AvtarName>
		<AvtarUrl>images/Avatar/lion150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>7</AvtarId>
		<AvtarName>truck-boy</AvtarName>
		<AvtarUrl>images/Avatar/mouse150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>8</AvtarId>
		<AvtarName>truck-boy</AvtarName>
		<AvtarUrl>images/Avatar/pig150x150.jpg</AvtarUrl>
	</Avtar>
	<Avtar>
		<AvtarId>9</AvtarId>
		<AvtarName>truck-boy</AvtarName>
		<AvtarUrl>images/Avatar/rabbit150x150.jpg</AvtarUrl>
	</Avtar>
</Avtars>

Code Explanation

  • <?xml version="1.0" encoding="utf-8" ?> This line indicates that this document is an XML file and specifies its version and character encoding.
  • <Avtars> is the root element of the XML document. It contains multiple <Avtar> elements, each representing an avatar.
  • <Avtar> is individual avatar elements. Each <Avtar> element contains the following child elements.
  • <AvtarId> is an element that stores a unique identifier for the avatar.
  • <AvtarName> is an element that stores a name or identifier for the avatar (e.g., "basketball-boy").
  • <AvtarUrl> is an element that stores the URL or path to the image file for the avatar (e.g., "images/Avatar/bird150x150.jpg").
  • <Avtar> elements are the XML file containing multiple <Avtar> elements, each representing a different avatar. In your example, there are nine avatars, each with a unique ID, name, and URL to an image file.

Step 3. Load images

Create a folder named 'images' inside the 'wwwroot' directory, and inside this folder, create one more folder named Avatar and load all the images specified in the XML file under this folder to show in a popup.

load image

Step 4. Define Avatar Model

Create an AvatarModel class to represent the avatar data. Create a class named AvatarModel.cs inside the Data folder, which is already present in the default project structure. This class will have properties for AvatarId, AvatarName, and AvatarUrl.

using System.Xml.Linq;
namespace DemoProject.Data
{
    public class AvatarModel
    {
        public int AvatarId { get; set; }
        public string AvatarName { get; set; }
        public string AvatarUrl { get; set; }
    }
}

Code Explanation

  • AvatarModel is a C# class representing an avatar model.
  • AvatarId is an integer property that likely represents a unique identifier for an avatar.
  • AvatarName is a string property that likely represents the name or identifier of an avatar (e.g., "basketball-boy").
  • AvatarUrl is a string property that likely represents the URL or path to the image file of the avatar (e.g., "images/Avatar/bird150x150.jpg").

Step 5. Load XML Data

Create a service to load avatar data from the XML file. Add a new class named AvatarService.cs inside the Data folder, which is already present in the default project structure.

using System.Xml.Linq;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace DemoProject.Data
{
    public class AvatarService
    {
        public List<AvatarModel> LoadAvatarsFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                // Handle the case where the file doesn't exist
                return new List<AvatarModel>();
            }
            XDocument xmlDoc = XDocument.Load(filePath);
            List<AvatarModel> avatars = xmlDoc.Descendants("Avtar")
                .Select(av => new AvatarModel
                {
                    AvatarId = (int)av.Element("AvtarId"),
                    AvatarName = (string)av.Element("AvtarName"),
                    AvatarUrl = Path.Combine("/", (string)av.Element("AvtarUrl"))
                })
                .ToList();
            return avatars;
        }
    }
}

Code Explanation

  • Namespace and Dependencies: The class begins by specifying the necessary namespaces and dependencies, including System.Xml.Linq, System.IO, System.Collections.Generic, and System.Linq.
  • Class Definition: This class, AvatarService, is intended to handle loading avatar data from an XML file.
  • LoadAvatarsFromFile Method: This method takes a filePath parameter, which is the path to the XML file containing avatar data. It returns a list of AvatarModel objects.
  • File Existence Check: It checks if the XML file exists at the specified filePath using File.Exists(filePath). If the file doesn't exist, it returns an empty list of avatars.
  • XML Loading: If the file exists, it loads the XML content from the file into an XDocument using XDocument.Load(filePath).
  • XML Parsing: It then parses the XML data by selecting all <Avtar> elements using xmlDoc.Descendants("Avtar"). For each <Avtar> element, it creates a new AvatarModel object and populates its properties using data from the XML elements: AvtarId, AvtarName, and AvtarUrl. It uses (int) and (string) casting to extract data from XML elements.
  • Path. Combine for URL: It uses Path.Combine("/," (string)av. Element("AvtarUrl")) to ensure that the AvatarUrl property is in a consistent format, starting with a forward slash /. This format is often used in web applications to represent relative URLs.
  • Returning Avatars: Finally, it returns a list of AvatarModel objects, effectively providing a collection of avatars loaded from the XML file.

Step 6. Render Avatars in the Popup

Inside the ModelPopup.razor component, you can render the avatars from the loaded XML data in the popup modal.

@using DemoProject.Data
@inject AvatarService avatarService

<div class="modal show taskmodalpopup" id="TaskModalPopUp" tabindex="-1" aria-hidden="true" style="display:@(IsShowEditPopup ? "block" : "none");">
    <div class="modal-dialog" style="width:50%">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Choose Your Avatar</h4>
                <button type="button" class="btn-close" @onclick="CloseModal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-2 task-statusbar">
                    @foreach (var avatar in avatars)
                    {
                        <div class="col-lg-4 col-md-6 col-sm-12">
                            <div class="avatar-item">
                                <img src="@avatar.AvatarUrl" alt="@avatar.AvatarName" class="img-fluid" />
                                <h6>@avatar.AvatarName</h6>
                                <!-- Add any other information you want to display for each avatar -->
                            </div>
                        </div>
                    }
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-danger" @onclick="CloseModal">Close</button>
            </div>
        </div>
    </div>
</div>

@code {
    [Parameter]
    public bool IsShowEditPopup { get; set; }

    [Parameter]
    public EventCallback OnClose { get; set; }

    private void CloseModal()
    {
        IsShowEditPopup = false;
        OnClose.InvokeAsync();
    }

    private List<AvatarModel> avatars;

    protected override void OnInitialized()
    {
        string xmlFilePath = "app_data\\avatar.xml";
        avatars = avatarService.LoadAvatarsFromFile(xmlFilePath);
    }
}

Code Explanation

  • Imports and Injection: The @using directive imports the DemoProject.Data namespace, making the AvatarService class available for injection using @inject AvatarService avatarService.
  • Modal Popup: The <div> element with class modal show taskmodalpopup represents the modal popup. Its visibility is controlled by the IsShowEditPopup property, which determines whether it should be displayed ("block") or hidden ("none").
  • Modal Content: Within the modal, you have a content structure that includes a title ("Choose Your Avatar") and a list of avatar items rendered in the body of the modal. The list of avatars is generated using a foreach loop that iterates over the avatars list retrieved from the XML file.
  • Close Modal Function: The CloseModal method is called when the close button is clicked. It sets IsShowEditPopup to false to hide the modal and invokes the OnClose event callback, allowing the parent component to respond to the modal closure.
  • Loading Avatars: In the OnInitialized lifecycle method, the component loads avatar data from an XML file specified by the xmlFilePath. The avatars are stored in the avatars list, which is used to populate the modal content.

Step 7. Create ModelPopup Component

Create a razor page inside the Pages folder named 'Demo. razor'. we can use the ModelPopup component within your /demo page to display avatar images in the modal popup when the "click here" button is clicked.

@page "/demo"
@using Microsoft.AspNetCore.Hosting
@inject IWebHostEnvironment WebHostEnvironment

@using DemoProject.Pages

<h3>This is demo model popup</h3>
<button class="btn btn-outline-dark" id="edit-profile" @onclick="Showpopup">click here</button>
<ModelPopup IsShowEditPopup="IsShowEditPopup" OnClose="CloseModal" />

@code {
    public bool IsShowEditPopup { get; set; }

    private void Showpopup()
    {
        IsShowEditPopup = true;
    }

    private void CloseModal()
    {
        IsShowEditPopup = false;
    }
}

Code Explanation

  • The @page "/demo" directive specifies the route at which this Blazor Server page will be accessible. In this case, it's the /demo route.
  • Namespace and Dependency Injection is the @using directive used to include Microsoft.AspNetCore.Hosting namespace, and the @inject directive injects an instance of IWebHostEnvironment into the page, making it available for use.
  • Within the page's content, there is an <h3> element that displays the text "This is demo model popup."
  • A <button> element is used with the text "click here." It has a @onclick attribute that calls the Showpopup method when the button is clicked.
  • The <ModelPopup> component is included. It takes two parameters: IsShowEditPopup and OnClose. The IsShowEditPopup parameter controls the visibility of the modal popup, and the OnClose parameter is an event callback that is triggered when the modal is closed.
  • @code Section contains the code-behind logic for the page.
  • IsShowEditPopup property that tracks whether the modal popup should be displayed or hidden. It is initially set to false.
  • Show popup () method that sets IsShowEditPopup to true when called, making the modal popup visible.
  • CloseModal() method that sets IsShowEditPopup to false when called, hiding the modal popup.

Step 8. Add navlink in the NavMenu.razor page

To display the demo page in the left navigation menu bar, we need to add a nav link that redirects to the /demo page.

<div class="nav-item px-3">
    <NavLink class="nav-link" href="demo">
        <span class="oi oi-arrow-circle-left" aria-hidden="true"></span> Demo
    </NavLink>
</div>

Code Explanation

  • <div class="nav-item px-3"> This <div> element represents a navigation item in a navigation menu. The class attribute specifies CSS classes for styling purposes, such as spacing (px-3).
  • <NavLink> is a Blazor component used for creating navigation links. It allows you to define links within your Blazor application.
  • class="nav-link" the class attribute specifies CSS classes for the link. In this case, nav-link is likely a CSS class that is applied to format the link as part of a navigation menu.
  • href="demo" attribute defines the destination URL that the link will navigate to. In this case, it navigates to the "demo" page or route within the application.
  • <span class="oi oi-arrow-circle-left" aria-hidden="true"></span> this <span> element contains an icon represented by the CSS classes oi oi-arrow-circle-left. Icons are often used for visual representation in navigation menus. The aria-hidden="true" attribute is used for accessibility, indicating that the icon is decorative and should be ignored by screen readers.
  • Demo is the text or label that will be displayed for the navigation link. In this case, it's the text "Demo."

Step 9. Add service to the program.cs

To display the demo page, we need to add a service in the program.cs file.

builder.Services.AddSingleton<AvatarService>();

After running the project, you will be able to see the following result.

blazor

Conclusion

In this article, you will learn how to create a feature in your Blazor Server application that lets users choose their profile pictures or avatars. We did this by loading avatar data from an XML file and displaying it in a popup window.

FAQs

Q1. What is Blazor?

Ans. Blazor is an open-source web framework developed by Microsoft that allows developers to build interactive web applications using C# and .NET instead of JavaScript. Blazor enables full-stack web development with a single programming language and runtime.

Q2. What are the two primary hosting models for Blazor?

Ans. There are two primary hosting models for Blazor.

Blazor WebAssembly

This model allows you to run Blazor applications directly in the web browser using WebAssembly, enabling code execution in the browser.

Blazor Server

In this model, the application's user interface is rendered on the server, and UI updates are sent to the client over a SignalR connection.

Q3. What is the purpose of the 'avatars.xml' file?

Ans. The 'avatars.xml' file stores avatar data in XML format. Each <Avtar> element represents an avatar and contains information such as AvatarId, AvatarName, and AvatarUrl. This file is used to populate the avatars in the popup.

Q4. How is the XML data loaded into the application?

Ans. The AvatarService class contains a method named LoadAvatarsFromFile, which reads the XML data from the 'avatars.xml' file. It parses the XML, creates AvatarModel objects, and stores them in a list for later use.

Q5. How are the avatar images rendered in the popup?

Ans. In the ModelPopup.razor component, avatars are rendered by iterating through the list of avatars and displaying each avatar's image, name, and additional information within the modal popup.


Similar Articles