How To Select an Avatar Image from Popup to Set as My Profile Picture In Blazor?

Introduction

In today's online world, making web applications personalized and engaging is important. A big part of this is letting users pick their profile pictures, which are the images that represent them on websites and in apps. Blazor, a web framework by Microsoft, makes it easy for developers to create interactive and dynamic web apps. In this article, we'll show you how to make a feature that lets users choose an avatar picture from a little popup window and set it as their profile picture in a Blazor app. We'll show you how to create this popup where users can view a variety of avatar pictures, pick one, and display it as their profile picture.

What is Blazor?

Blazor is a web framework created by Microsoft. It lets developers build interactive web apps using C# and .NET instead of the more commonly used JavaScript. With Blazor, you can do both the front-end and back-end of web development using a single programming language and system.

Prerequisites

Before we dive into the implementation, ensure you have the following prerequisites in place:

  • Basic knowledge of C# and Blazor.
  • A working Blazor application project.
  • Some avatar images are ready to be used.

Step 1. Creating XML Data, Loading XML Data, Loading Images, and Defining the Avatar Model.

First, let's get comfortable with creating and using XML data and setting up the avatar model. You can learn all these essential steps by reading my article How to Display Avatar Images from XML Data in Blazor This article will give you the knowledge you need to work with XML data, load pictures, and define the avatar model in a simple and straightforward way.

Step 2. Define the 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 3. Display Avatars in the Popup and Choose One as Your Profile Picture.

Inside the ModelPopup.razor component, you can render the avatars from the loaded XML data in the popup modal, and you can also choose one as your profile picture.

@using DemoProject.Data
@inject AvatarService avatarService
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">

<img src="@selectedAvatarUrl" alt="avatar" class="img-fluid avatar-image" />

@*<button class="btn-light" id="edit-profile" @onclick="Showpopup"></button>*@

<button class="btn-light" id="edit-profile" @onclick="Showpopup">
    <i class="fas fa-pencil-alt"></i>
</button>

<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">
                                <button class="btn-light" @onclick="() => SelectAvatar(avatar)">
                                    <img src="@avatar.AvatarUrl" alt="@avatar.AvatarName" class="img-fluid" />
                                    <h6>@avatar.AvatarName</h6>
                                    <!-- Add a button to select this avatar -->
                                </button>
                            </div>
                        </div>
                    }
                </div>
            </div>
            <div class="modal-footer">
                <InputFile OnChange="HandleImageUpload" id="fileinput" class="custom-input-hide"></InputFile>
                <button type="button" class="btn btn-danger" @onclick="CloseModal">Close</button>
            </div>
        </div>
    </div>
</div>

@code {
    public string selectedAvatarUrl { get; set; }
    [Parameter]
    public bool IsShowEditPopup { get; set; }
    [Parameter]
    public EventCallback OnClose { get; set; }

    private void Showpopup()
    {
        IsShowEditPopup = true;
    }

    private void CloseModal()
    {
        IsShowEditPopup = false;
    }

    private List<AvatarModel> avatars;

    protected override void OnInitialized()
    {
        // Specify the path to your XML file
        string xmlFilePath = "app_data\\avatar.xml";
        avatars = avatarService.LoadAvatarsFromFile(xmlFilePath);
    }

    private async Task HandleImageUpload(InputFileChangeEventArgs e)
    {
        var imageFile = e.File;

        if (imageFile != null)
        {
            // Generate a unique file name or use the user's ID for naming
            string uniqueFileName = Guid.NewGuid().ToString() + "_" + imageFile.Name;

            // Get the path where you want to save the image (e.g., wwwroot/avatars/)
            string imagePath = "wwwroot/avatars/" + uniqueFileName;
            // Save the image to the specified path
            using (var stream = new FileStream(imagePath, FileMode.Create))
            {
                await imageFile.OpenReadStream().CopyToAsync(stream);
            }
            selectedAvatarUrl = imageFile.Name;
        }
        // Update user's profile with the avatar information

    }
    private void SelectAvatar(AvatarModel avatar)
    {
        selectedAvatarUrl = avatar.AvatarUrl; // Set the selected avatar's URL as the profile picture

    }

}

Code Explanation

Using Statements and Injecting Services

  • @using DemoProject.Data is an import statement for using the AvatarModel data.
  • @inject AvatarService avatarService injects an AvatarService to handle loading avatars from XML.

Font Awesome and Avatar Image Display

  • A reference to the Font Awesome stylesheet is included using an external URL.
  • An <img> element displays the selected avatar image, and a pencil button (<i class="fas fa-pencil-alt"></i>) is provided for editing.

Popup Modal

  • A modal dialog is used to create the popup effect for avatar selection.
  • The modal's visibility is controlled using the IsShowEditPopup parameter, with CSS style "display:@(IsShowEditPopup ? "block" : "none").

Avatar Selection

  • A list of avatar options is displayed within the modal.
  • For each avatar, an image, its name, and a button to select it are provided.
  • Clicking an avatar button triggers the SelectAvatar(avatar) method to set the selected avatar's URL.

File Upload

  • An <InputFile> component allows users to upload their custom avatar images.
  • The HandleImageUpload method handles the file upload. It saves the image with a unique name and updates the selected avatar URL.

Component Parameters

  • IsShowEditPopup is a parameter that controls the visibility of the popup.
  • OnClose is an event callback for when the popup is closed.

Code Block

  • Showpopup() is a method that sets IsShowEditPopup to true, showing the popup.
  • CloseModal() sets IsShowEditPopup to false, hiding the popup.
  • OnInitialized() is an override method that loads avatar data from an XML file using the avatarService.

Step 4. Creating a ModelPopup Component and Displaying the Selected Profile Picture in the Left Navigation Menu Bar.

Now that you've gained some basic knowledge of Blazor components and learned how to display avatar images from XML data in my previous article, you'll need to create a ModelPopup Component and insert specific code within the NavMenu.razor page.

<div class="user-profile">
    <div class="user-avatar">
        <label for="fileinput">
            <ModelPopup IsShowEditPopup="IsShowEditPopup" OnClose="CloseModal"></ModelPopup>
        </label>
    </div>
</div>

Code Explanation

  • <ModelPopup IsShowEditPopup="IsShowEditPopup" OnClose="CloseModal"></ModelPopup> is the interesting part. It's an instance of a ModelPopup component. This component is used to create a popup for selecting or uploading a profile picture. It takes two parameters:
  • IsShowEditPopup is a parameter that controls the visibility of the popup. It seems to determine whether the popup is displayed or not.
  • OnClose is an event callback that likely handles closing the popup.

Now, we need to add the following code to the code section within NavMenu.razor page.

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

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

Code Explanation

  • public bool IsShowEditPopup { get; set; } is a public property that defines a boolean variable named IsShowEditPopup. It's used to control the visibility of a popup or modal. When IsShowEditPopup is true, the popup is displayed, and when it's false, the popup is hidden.
  • private void CloseModal() is a private method named CloseModal. It is invoked to close the popup by setting IsShowEditPopup to false. When called, this method hides the popup by changing the value of IsShowEditPopup to false.

Step 5. Add service to the program.cs.

To show avatar images in the popup, we need to add a service to the program.cs file.

builder.Services.AddSingleton<AvatarService>();

Step 6. Adding CSS to site.css for a Stylish Display of the Selected Profile Picture.

In this step, you'll enhance the appearance of the selected profile picture by applying CSS styles in the site.css file. This will ensure that the image looks great and seamlessly integrates with your application's design.

.user-profile {
    width: 100%;
    height: 120px;
    display: flex;
    text-align: center;
    flex-flow: column;
    align-items: center;
    text-align: center;
    margin-top: 20px;
}
.user-avatar {
    width: 150px;
    height: 150px;
    position: relative;
    border: 4px solid #ffffff;
}
.user-avatar {
    width: 120px;
    height: 120px;
}
a.edit-profile
 {
    position: absolute;
    bottom: 5px;
    right: 0px;
    width: 32px;
    height: 32px;
    background: whitesmoke;
    padding: 5px;
    color: #fff;
}
#edit-profile {
    position: absolute;
    bottom: -15px;
    right: -17px;
    width: 32px;
    height: 32px;
    background: whitesmoke;
    padding: 5px;
  
}

#fileinput {
    margin-right: 82px
}

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

output

Conclusion

With Blazor, creating a popup for selecting an avatar image and setting it as your profile picture is a straightforward task. By following these steps, you can provide your users with a more personalized and engaging experience, helping them to better connect with your application. This customization adds a touch of individuality to their profiles and enhances their overall user experience.

FAQ's

Q 1. What is Blazor, and why is it used for web development?

A. Blazor is a web framework developed by Microsoft that enables developers to build interactive web applications using C# and .NET instead of JavaScript. It simplifies web development by allowing both front-end and back-end coding in a single programming language and system.

Q 2. How can I create a ModelPopup component for avatar selection in Blazor?

A. To create a ModelPopup component for avatar selection, you can define the component's structure and functionality using Blazor code and HTML. This component displays a list of available avatar images and provides a way for users to choose one to set as their profile picture.

Q 3. Why is the AvatarService registered as a singleton service in the Blazor application?

A. Registering the AvatarService as a singleton service ensures that there is a single, centralized service instance for handling avatar-related functionality. This promotes efficiency, resource management, and data consistency across the application. It also allows various parts of the application to access and work with avatar data consistently.

Q 4. How can users upload their custom avatar images in the ModelPopup component?

A. Users can upload custom avatar images by clicking on the "Choose File" button within the ModelPopup component. When they select an image file, it is uploaded and stored with a unique name, and the selected avatar URL is updated to the newly uploaded image.


Similar Articles