Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (161).NET Core  (29).NET MAUI  (63)Angular  (74)ASP.NET  (50)ASP.NET Core  (79)ASP.NET MVC  (88)Azure  (36)Blazor  (152)DocIO  (23)Essential JS 2  (84)Essential Studio  (172)File Formats  (28)Flutter  (123)JavaScript  (186)Microsoft  (113)PDF  (67)React  (61)Succinctly series  (128)Syncfusion  (609)TypeScript  (31)Uno Platform  (3)UWP  (4)Vue  (39)Webinar  (35)Windows Forms  (59)WinUI  (52)WPF  (138)Xamarin  (155)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (5)Build conference  (6)Business intelligence  (54)Button  (4)C#  (119)Chart  (57)Cloud  (12)Company  (445)Dashboard  (8)Data Science  (3)Data Validation  (6)DataGrid  (55)Development  (394)Doc  (7)DockingManager  (1)eBook  (96)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (18)File Manager  (4)Gantt  (11)Gauge  (11)Git  (4)Grid  (28)HTML  (10)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (311)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (30)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (22)Solution Services  (3)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (92)UI  (224)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (23)Visual Studio Code  (16)Web  (371)What's new  (213)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
5 Simple Steps to Create a Blazor Component

5 Simple Steps to Create a Blazor Component

The Blazor framework allows developers to build interactive web UI using C# instead of JavaScript. Blazor applications are built using multiple Blazor components. Each Blazor component is a Razor component consisting of an HTML and CSS template and C# code. These components are then a portion of the UI that can be shared, reused in an app, and even reused in multiple apps.

In this blog, we are going to see how to create a reusable Blazor component. We will use the standard Blazor Server application template of Visual Studio 2022.

Prerequisites

To create and run a Blazor server-side web app, we need the following:

Note:

  • .NET Core SDK 3.1.8 requires Visual Studio 2019 16.7 or later.
  • .NET 5.0 requires Visual Studio 2019 16.8 or later.
  • .NET 6.0 requires Visual Studio 2022 17.0 Preview 4.1 or later.

Let’s see how to create a Blazor component to display the employee details of an organization.

Step #1: Create a Blazor server-side app.

First, open Visual Studio and create a Blazor server-side project.

Step #2: Create the EmployeeCard component.

Let’s create a Blazor component to display details about the employees of an organization.

To add a component to the project, right-click on the Pages folder and choose Add -> Razor Component.

Refer to the following image.

Add Razor Component to Blazor Server AppIn the Add New Item- Blazor App dialog, provide the name EmployeeCard and click Add.

Syncfusion’s Blazor components suite is the expert’s choice for building modern web apps.

Refer to the following image.

Naming the Razor component as EmployeeCard

Now, our employee component is created with the following basic template.

<h3>EmployeeCard</h3>

@code {

}

Next, we replace this code with our UI code for the employee details. The markup contains div, h6, h5, and img elements. The Blazor Server app project has a Bootstrap theme, so we are going to use the Bootstrap Card to display the organized content.

Refer to the following code.

<div class="card m-2">
  <div class="card-body">
    <h6 class="card-title text-center">Digital Marketing</h6>
    <h6 class="card-subtitle mb-2 text-muted text-center">Sales Department</h6>
    <div class="card-text text-center">
        <img class="card-img-top" src="../EmployeeImage.png" alt="Card image cap">
        <h5>Margaret</h5>
    </div>
    <div>                
     <h6 class="card-text"><b>ID</b>: <small>124</small></h6>                 
     <h6 class="card-text"><b>Joined</b>: <small>12th July 2012</small> </h6>               
     <h6 class="card-text"><b>Email</b>: <small>margaret@domain.com</small></h6>
   </div>
         
  </div>
</div>

Step #3: Create the parameters to reuse the Blazor component.

Our component is ready. But we have used hard-coded values for the employee details like image, ID, name, and email. A component is a piece of an app that can be used multiple times in the same app.

So, to make our component more dynamic, we replace the hard-coded values with the component parameters provided by the user. Now let’s create the parameters to get these details.

Refer to the following code.

@code {

   [Parameter]
   public string Name {get; set;}

   [Parameter]
   public string Image {get; set;}

   [Parameter]
   public int ID {get; set;}

   [Parameter]
   public string Joined {get; set;}

   [Parameter]
   public string Email {get; set;}

  
}

Then, in the Razor page, replace the hard-coded values with the parameters’ values by prefixing @ to them.

Refer to the following code.

<div class="card m-2">
 <div class="card-body">
    <h6 class="card-title text-center">Digital Marketing</h6>
    <h6 class="card-subtitle mb-2 text-muted text-center">Sales Department</h6>
    <div class="card-text text-center">
        <img class="card-img-top" src="@Image" alt="Card image cap">
        <h5>@Name</h5>
    </div>
    <div>
    <h6 class="card-text"><b>ID</b>  : <small>@ID</small></h6>                 
    <h6 class="card-text"><b>Joined</b>: <small>@Joined</small> </h6>
    <h6 class="card-text"><b>Email</b>: <small>@Email</small></h6>
    </div>
         
 </div>
</div>

@code {

   [Parameter]
   public string Name {get; set;}

   [Parameter]
   public string Image {get; set;}

   [Parameter]
   public int ID {get; set;}

   [Parameter]
   public string Joined {get; set;}

   [Parameter]
   public string Email {get; set;}
  
}

Now, move the EmployeeCard.Razor file to the Shared folder.

Step #4: Display the employee details.

Now, our Blazor component is ready to be displayed on a page. We can treat the Blazor component itself as a page using the route directives. As of now, we are using the default Index.razor page to display the component.

Use the HTML tag with the component name <EmployeeCard></EmployeeCard> within the Index page and pass the values to the component parameters.

@page "/"

<EmployeeCard Image="../EmployeeImage.png" ID="124" Joined="12th July 2012" Email="margaret@domain.com"></EmployeeCard>

Then, run the application and you will see our Blazor component on the index page itself.

Displaying Single Employee's Details in a Department

Step #5: Display multiple employees’ details in a department.

We have displayed the information of just a single employee. But we can use this EmployeeCard component to display the details of all the employees in an organization.

Let’s change this page to show the details of the employees working in the Sales Department of the organization.

First, create a Model and Service in the /Data folder of the project to generate some random data for the employees.

In the EmployeeModel, declare the fields.

Everything a developer needs to know to use Blazor components in the Blazor app is completely documented.

EmployeeModel

public class EmployeeModel
 {
     public int ID { get; set; }
     public DateTime Joined { get; set; }
     public string Name { get; set; } = "";
     public string Image { get; set; } = "";
     public string Email { get; set; } = "";
 }

In the EmployeeService, define the method to generate data.

EmployeeService

public class EmployeeService
 {
        private static readonly string[] Name = new[]
        {
        "Nancy", "Margaret", "Michael", "Robert", "Anne" 
        };
        private static readonly string[] Mail = new[]
        {
        "nancy@domain.com", "margaret@domain.com", "michael@domain.com", "robert@domain.com","anne@domain.com"
        };

        public Task<EmployeeModel[]> GetEmployeeAsync(DateTime startDate)
        {
            return Task.FromResult(Enumerable.Range(0, 5).Select(index => new EmployeeModel
            {
              Joined = startDate.AddDays(index),
              Name = Name[index],
              Email = Mail[index],
              Image = "../" + Name[index] +".PNG",
              ID = Random.Shared.Next(200, 555)

            }).ToArray());
        }
 }

Then, register the EmployeeService in the Program.cs file to make it available for all the components in the project.

Program.CS

builder.Services.AddSingleton<EmployeeService>();

Inject the EmployeeService in the index page using the @inject directive. Now, the service is available on the index page. Call the GetEmployeeAsync method to generate the array of the Employee model.

Declare the employeeDetails field to store the data from the service. The data should be loaded when the component is initialized, so use the OnInitializedAsync lifecycle method to get the values.

@using BlazorApp.Data
@inject EmployeeService EmployeeService

@code {
    private EmployeeModel[]? employeeDetails;

    protected override async Task OnInitializedAsync()
    {
        employeeDetails = await EmployeeService.GetEmployeeAsync(DateTime.Now);
    }
}

Using the employee details array, create components for each employee and assign the details from the employee service as values of the parameters.

Explore the different application UIs developed using Syncfusion Blazor components.

Refer to the following code.

@page "/"

@using BlazorApp.Data
@inject EmployeeService EmployeeService

@if (employeeDetails == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <div class="container">
    <div class="row">       
   @foreach (var employee in employeeDetails)
   {
      <div class="col-lg-4 mb-2">
      <EmployeeCard Name=@employee.Name Image=@employee.Image ID=@employee.ID Joined=@employee.Joined.ToShortDateString() Email=@employee.Email></EmployeeCard>
     </div>
   }  
   </div>
   </div>
}

@code {
    private EmployeeModel[]? employeeDetails;

    protected override async Task OnInitializedAsync()
    {
        employeeDetails = await EmployeeService.GetEmployeeAsync(DateTime.Now);
    }
}

Finally, run the application and you can see the details of the employees in the sales department.

Displaying Multiple Employees' Details in a DepartmentYou can use this Blazor component to display all the employee details in the organization in each department.

GitHub reference

For more details, refer to the complete code example on GitHub for creating a Blazor component.

Conclusion

Thanks for reading! I hope you now have a better understanding of how to create a Blazor component. The UI components are the heart of a Blazor application, as they let us reuse the code, reduce our development time, and enhance our productivity. Use this blog post as a reference and try creating your own Blazor component. Leave your feedback in the comments section below!

The Syncfusion Blazor suite offers over 70 components that work with both Blazor server-side and client-side (Blazor WebAssembly) projects seamlessly. Use them to build astonishing applications!

For existing customers, the newest version of Essential Studio is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out the available features.

For questions, you can contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top