Introduction
In our web applications, we often need to display a pop up to add a new entity. This pop up is validated and managed using Ja avascript framework.
In this article we will be using Blazor Web assembly and C# to create our modal popup as Blazor component and use it in any page.
We will also do data validations on this pop-up using C# without the use of JavaScript.
Once the data is validated using API it will be saved in SQL database.
Prerequisites
This article assumes you have a basic working knowledge of Blazor web assembly and .NET Core.
Through this article, we will cover the following topics,
- How to create custom modal pop up component in Blazor?
- How to use custom component on any razor pages?
- How to call Data service in Blazor app and save user data using Entity Framework core?
Output
Application with Modal popup will look like below,
Pop Up Validations
Implementation
Before implementation, you need to know the prerequisite.
We need to create a new Blazor web assembly project with .NET Core hosted.
The basic project structure is as shown below.
- EmployeePortal.Client is Blazor Web assembly Project
- EmployeePortal.Server is .NET Core 3.1 Project Where our API and Database Repository would reside
- EmployeePoral.Shared is .NET Standard Library Project which would hold the required Models for our project
Creating the modal component
Create a new component folder in our client project and add new Razor component.The detailed structure of client folder is mentioned below.
Add the below code in AddEmployeeDialog.razor
- @if (ShowDialog)
- {
-
- <div class="modal fade show d-block" id="exampleModal" tabindex="-1" role="dialog">
- <div class="modal-dialog" role="document">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title" id="titleLabel">Add Employee</h5>
- <button type="button" class="close" @onclick="@Close" data-dismiss="modal" aria-label="Close">
- <span aria-hidden="true">×</span>
- </button>
- </div>
- <div class="modal-body">
- <EditForm Model="@Employee" OnValidSubmit="@HandleValidSubmit">
- <DataAnnotationsValidator />
- <ValidationSummary />
- <div class="form-group">
- <label for="lastName">Last name: </label>
- <InputText id="lastName" class="form-control" @bind-Value="@Employee.LastName" placeholder="Enter last name"></InputText>
- <ValidationMessage For="@(() => Employee.LastName)" />
- </div>
- <div class="form-group">
- <label for="firstName">First name: </label>
- <InputText id="firstName" class="form-control" @bind-Value="@Employee.FirstName" placeholder="Enter first name"></InputText>
- <ValidationMessage For="@(() => Employee.FirstName)" />
- </div>
- <div class="form-group">
- <label for="email">Email: </label>
- <InputText id="email" class="form-control" @bind-Value="@Employee.Email" placeholder="Enter email"></InputText>
- <ValidationMessage For="@(() => Employee.Email)" />
- </div>
- <button type="submit" class="btn btn-primary">Save employee</button>
- <a class="btn btn-outline-primary" @onclick="@Close">Close</a>
- </EditForm>
- </div>
- </div>
- </div>
- </div>
- }
Add the below code in AddEmployeeDialog.cs
- This is our component class which would invoke EmployeeDataservice
- Which would inturn call .NET Core API using System
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using EmployeePortal.Shared;
- using EmployeePortal.Client.Services;
- using Microsoft.AspNetCore.Components;
- namespace EmployeePortal.Client.Components {
- public partial class AddEmployeeDialog: ComponentBase {
- public Employee Employee {
- get;
- set;
- } = new Employee {};
- [Inject]
- public IEmployeeDataService EmployeeDataService {
- get;
- set;
- }
- public bool ShowDialog {
- get;
- set;
- }
- [Parameter]
- public EventCallback < bool > CloseEventCallback {
- get;
- set;
- }
- public void Show() {
- ResetDialog();
- ShowDialog = true;
- StateHasChanged();
- }
- public void Close() {
- ShowDialog = false;
- StateHasChanged();
- }
- private void ResetDialog() {
- Employee = new Employee {};
- }
- protected async Task HandleValidSubmit() {
- await EmployeeDataService.AddEmployee(Employee);
- ShowDialog = false;
- await CloseEventCallback.InvokeAsync(true);
- StateHasChanged();
- }
- }
- }
Validate and Save Capture Data using Data service and .NET Core API
Create a new Service Folder and Add new Employee Service
Register Data service in program.cs of client project
- builder.Services.AddHttpClient<IEmployeeDataService, EmployeeDataService>(client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
Data Service would have AddEmployee function as below which would call the .NET Core API
- public async Task < Employee > AddEmployee(Employee employee) {
- var employeeJson = new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
- var response = await _httpClient.PostAsync($ "api/employee", employeeJson);
- if (response.IsSuccessStatusCode) {
- return await JsonSerializer.DeserializeAsync < Employee > (await response.Content.ReadAsStreamAsync());
- }
- return null;
- }
In .NET Core Project create a new API contoller as below
- [Route("api/employee")]
- [HttpPost]
- public IActionResult CreateEmployee([FromBody] Employee employee) {
- if (employee == null) return BadRequest();
- if (employee.FirstName == string.Empty || employee.LastName == string.Empty) {
- ModelState.AddModelError("Name/FirstName", "The name or first name shouldn't be empty");
- }
- if (!ModelState.IsValid) return BadRequest(ModelState);
- var createdEmployee = _employeeRepository.AddEmployee(employee);
- return Created("employee", createdEmployee);
- }
Register Repository in Startup.cs
- services.AddScoped<IEmployeeRepository, EmployeeRepository>();
- }
Repository to save data in database
- public Employee AddEmployee(Employee employee) {
- var addedEntity = _appDbContext.Employees.Add(employee);
- _appDbContext.SaveChanges();
- return addedEntity.Entity;
- }
Using our custom Created component on home page
Create a new razor page Employee and important component using this syntax
- @page"/"
- @using EmployeePortal.Client.Components;
- <button@onclick="QuickAddEmployee"class="btn btn-dark table-btn quick-add-btn"> + </button>
- <AddEmployeeDialog@ref="AddEmployeeDialog"></AddEmployeeDialog>
The page class is as below.
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- namespace EmployeePortal.Shared {
- [Table("Employee")]
- public partial class Employee {
- public int EmployeeId {
- get;
- set;
- }
- [Required]
- [StringLength(50, ErrorMessage = "First name is too long.")]
- public string FirstName {
- get;
- set;
- }
- [Required]
- [StringLength(50, ErrorMessage = "Last name is too long.")]
- public string LastName {
- get;
- set;
- }
- [Required]
- [EmailAddress]
- public string Email {
- get;
- set;
- }
- public string Street {
- get;
- set;
- }
- public string Zip {
- get;
- set;
- }
- public string City {
- get;
- set;
- }
- public string PhoneNumber {
- get;
- set;
- }
- [StringLength(1000, ErrorMessage = "Comment length can't exceed 1000 characters.")]
- public string Comment {
- get;
- set;
- }
- }
- }
Summary
Through this article we have learned how to create Custom Blazor component modal and validate user input. This also covers how to save capture data into SQL db using .NET Core API.
Thanks a lot for reading. I hope you liked this article. Please share your valuable suggestions and feedback. Write in the comment box in case you have any questions. Have a good day!