Forms in Blazor
In this article, we will explore forms in Blazor,
A Blazor provides a special component called EditForm. EditForm makes it easy to create a form with entities so for defining form we need to first define entity let’s take the example of product creation were we defined the product entity class as below,
Product.cs
using System;using System.Collections.Generic;using System.Text;namespace EmployeeManagement{public class Product{public int productId { get; set; }public string ProductName { get; set; }}}
CreateProduct.razor
@page “/createProduct”<h3>Create Product</h3><EditForm Model=”product” OnSubmit=”Create”><div class=”form-group”><label>Name:</label><div><InputText class=”form-control” @bind-Value=”@product.ProductName”></InputText></div></div><button class=”btn btn-success” type=”submit”>Create Product</button></EditForm>@code {private Product product=new Product();private void Create(){//logic for saving data at table}}
As you see over here EditForm component is used were we pass product model to it and defined OnSubmit Event which will hit create a method to perform an operation on data also for defining Input type text we have used InputText component of blazor which comes up with some additional functionalities like highlighting a textbox.
With the OnSubmit EditForm component come up with other two events called OnValidSubmit and OnInvalidSubmit.
Validations rules allow us to define the rule which our application should before taking any action. We can define this validation at on entity classes as shown below,
public class Product{public int productId { get; set; }[Required]public string ProductName { get; set; }}
To use this validation in razor component you need to add <DataAnnotationValidator/> and to display the error message add <ValidationMessage/> as shown below,
<EditForm Model=”product” OnValidSubmit=”Create”><DataAnnotationsValidator/><div class=”form-group”><label>Name:</label><div><InputText class=”form-control” @bind-Value=”@product.ProductName”></InputText><ValidationMessage For=”@(()=>product.ProductName)”></ValidationMessage></div></div><button class=”btn btn-success” type=”submit”>Create Product</button></EditForm>
Thank You, See you in the next article !!
You can reach out to me here,
LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar
Email: vaibhavbhapkar.medium@gmail.com
If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/