Site icon Tutexchange

HOW TO EDIT AND UPDATE FORM IN BLAZOR

Advertisements

Here, you’ll learn how to Edit and Update User Details in Blazor using Entity Framework core.

PART 1:- Simple CRUD Operation With Blazor And Entity Framework Core

PART 2:- Simple Grid View with Blazor and Entity Framework Core

Complete Source Code on Github

We will redirect to the Edit page from the Grid page by clicking on the Edit button.

Below is the Grid view which we have created in Part of the CRUD operation.

Project structure

Adding UserMasterEditViewModel in BlazorPlayGround.ViewModel Class Library

In BlazorPlayGround.ViewModel Class Library we are going to add a class with Name UserMasterEditViewModel and add properties init.

This ViewModel will be used for creating a form for taking Inputs.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BlazorPlayGround.ViewModel
{
    public class UserMasterEditViewModel
    {
        public int UserId { get; set; }

        [Required(ErrorMessage = "First Name is Required")]
        [RegularExpression("^[a-zA-Z ]*$", ErrorMessage = "Enter Valid First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is Required")]
        [RegularExpression("^[a-zA-Z ]*$", ErrorMessage = "Enter Valid First Name")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Middle Name is Required")]
        [RegularExpression("^[a-zA-Z ]*$", ErrorMessage = "Enter Valid First Name")]
        public string MiddleName { get; set; }

        [Required(ErrorMessage = "Address is Required")]
        public string Address { get; set; }

        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Enter valid Email Id")]
        [Required(ErrorMessage = "EmailId is Required")]
        public string EmailId { get; set; }

        [Display(Name = "MobileNo")]
        [RegularExpression(@"^[7-9][0-9]{9}$", ErrorMessage = "Enter Mobileno.")]
        [Required(ErrorMessage = "MobileNo Required")]
        public string MobileNo { get; set; }

        [Display(Name = "Gender")]
        [Required(ErrorMessage = "Gender Required")]
        public string GenderId { get; set; }
        public List<SelectListItem> ListofGender { get; set; }
        public bool Status { get; set; }
    }
}

Adding GetUserDetailsforEdit Method in Interface IUserMasterQueries in BlazorPlayGround.Data Class Library

UsersEditViewModel GetUserDetailsforEdit(int userId)

Implementing GetUserDetailsforEdit method in UserMasterCommand class in BlazorPlayGround.Data Class Library

public UsersEditViewModel GetUserDetailsforEdit(int userId)
{
            try
            {
                var edituser = (from usermaster in _blazorPlayGroundContext.UserMaster.AsNoTracking()
                                where usermaster.UserId == userId
                                select new UsersEditViewModel()
                                {
                                    FirstName = usermaster.FirstName,
                                    Address = usermaster.Address,
                                    EmailId = usermaster.EmailId,
                                    GenderId = usermaster.GenderId.ToString(),
                                    LastName = usermaster.LastName,
                                    MiddleName = usermaster.MiddleName,
                                    MobileNo = usermaster.MobileNo,
                                    Status = usermaster.Status,
                                    UserId = usermaster.UserId
                                }
                    ).FirstOrDefault();

                return edituser;
            }
            catch (Exception)
            {
                throw;
            }
}

Adding Component

We are going to add a Component with the name EditUserComponent.razor

Adding Base Class for EditUserComponentBase Component

We will add a class with the name EditUserComponentBase, and then we will inherit it with ComponentBase.

Next, we are going to add a property in the EditUserComponentBase component.

Adding Property and Injecting dependencies

Injecting Dependency of IUserMasterQueries for accessing data to bind Edit Page.

Injecting Dependency of IUserMasterCommand for Updating User Data by calling Update method.

IJSRuntime Service is used to invoke any JavaScript function from .NET code.

NavigationManager Service is used for managing URIs and navigation.

[Inject] public IJSRuntime JsRuntime { get; set; }
[Inject] NavigationManager NavManager { get; set; }
[Inject] private IUserMasterQueries UserMasterQueries { get; set; }
[Inject] private IUserMasterCommand UserMasterCommand { get; set; }
using BlazorPlayGround.Data.UserMasters.Command;
using BlazorPlayGround.Data.UserMasters.Queries;
using BlazorPlayGround.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace BlazorPlayGround2.Pages
{
    public class EditUserComponentBase : ComponentBase
    {
        [Inject] public IJSRuntime JsRuntime { get; set; }
        [Inject] private IUserMasterQueries UserMasterQueries { get; set; }
        [Inject] private IUserMasterCommand UserMasterCommand { get; set; }
        [Inject] NavigationManager NavManager { get; set; }
        public UserMasterEditViewModel UserMasterVM { get; set; } = new UserMasterEditViewModel();      
    }
}

Next, our EditUserComponent will receive the Id parameter from another component. For that, we will add the Id parameter and decorate it with the [Parameter] attribute.

[Parameter] public int Id { get; set; }
public class EditUserComponentBase : ComponentBase
{
    [Inject] public IJSRuntime JsRuntime { get; set; }
    [Inject] private IUserMasterQueries UserMasterQueries { get; set; }
    [Inject] private IUserMasterCommand UserMasterCommand { get; set; }
    [Inject] NavigationManager NavManager { get; set; }
    public UserMasterEditViewModel UserMasterVM { get; set; } = new UserMasterEditViewModel();                
    [Parameter] public int Id { get; set; }
}

OnInitialized Method

Next, we will bind data to form in the OnInitialized method, where we can access the Id parameter, which will get value from the URL parameter.

For critical data in Edit Mode, we need to data by UserId (Id) and then assign it to UsersVM ViewModel (UserMasterEditViewModel). Along with that, we are going to bind ListofGender.

 protected override void OnInitialized()
 {
     UserMasterVM = UserMasterQueries.GetUserDetailsforEdit(Id);
     UserMasterVM.ListofGender =  new List<SelectListItem>()
     {
         new SelectListItem()
         {
             Text="Select",
             Value =""
         },
         new SelectListItem()
         {
             Text="Male",
             Value ="1"
         },
         new SelectListItem()
         {
             Text="Female",
             Value ="2"
         }
     };
 }

Next, we will add the Event Callback method FormSubmitted which will be invoked when a form is successfully submitted without any validation error.

Adding Method Form Submitted

This method will get called when the form is submitted without any validation error.

Using JsRuntime, we are going to show a confirmation dialogue box. If the user confirms it, we will create the UserMasterModel object and pass it to the Update method of the UserMasterCommand Concrete class.

 protected async void FormSubmitted()
 {
     bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure you Want to Update User Details?"); 
     if (confirmed)
     {

         var userMaster = new UserMasterModel()
         {
             Address = UserMasterVM.Address,
             EmailId = UserMasterVM.EmailId,
             FirstName = UserMasterVM.FirstName,
             GenderId = Convert.ToInt32(UserMasterVM.GenderId),
             LastName = UserMasterVM.LastName,
             MiddleName = UserMasterVM.MiddleName,
             MobileNo = UserMasterVM.MobileNo,
             Status = UserMasterVM.Status,
             UserId = UserMasterVM.UserId,

         };

         UserMasterCommand.Update(userMaster);
         NavManager.NavigateTo("UserGrid", false);

     }
     else
     {
         await JsRuntime.InvokeVoidAsync("showAlert", "Cancel");
     }
 }

Next, we are going to work on EditUserComponent.razor page, which we have added earlier.

EditUserComponent.razor page

@page "/EditUser/{Id:int}"

We have added constraints for the Id parameter, which will only allow valid integer values.

@page "/EditUser/{Id:int}"
@inherits EditUserComponentBase

<div class="col-md-12">
    <EditForm Model="@UserMasterVM" OnValidSubmit="@FormSubmitted">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title">Edit</h5>
            </div>
            <div class="card-body">

       
                <input value="@UserMasterVM.UserId" type="hidden" />
                <DataAnnotationsValidator />
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label for="FirstName">First Name: </label>
                        <InputText id="FirstName" class="form-control" @bind-Value="@UserMasterVM.FirstName" placeholder="Enter First name"></InputText>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.FirstName)" />
                    </div>
                    <div class="form-group col-md-4">
                        <label for="MiddleName">Middle Name: </label>
                        <InputText id="MiddleName" class="form-control" @bind-Value="@UserMasterVM.MiddleName" placeholder="Enter Middle name"></InputText>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.MiddleName)" />
                    </div>

                    <div class="form-group col-md-4">
                        <label for="LastName">Last Name: </label>
                        <InputText id="LastName" class="form-control" @bind-Value="@UserMasterVM.LastName" placeholder="Enter Last name"></InputText>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.LastName)" />
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label for="Address">Address: </label>
                        <InputTextArea id="Address" class="form-control" @bind-Value="@UserMasterVM.Address" placeholder="Enter Address"></InputTextArea>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.Address)" />
                    </div>
                    <div class="form-group col-md-4">
                        <label for="EmailId">EmailId: </label>
                        <InputText id="EmailId" class="form-control" @bind-Value="@UserMasterVM.EmailId" placeholder="Enter EmailId"></InputText>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.EmailId)" />
                    </div>
                    <div class="form-group col-md-4">
                        <label for="MobileNo">MobileNo: </label>
                        <InputText id="MobileNo" class="form-control" maxlength="10"
                                   @bind-Value="@UserMasterVM.MobileNo"
                                   placeholder="Enter MobileNo"></InputText>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.MobileNo)" />
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label for="GenderId">Gender</label>
                        <InputSelect id="GenderId" class="form-control"
                                     @bind-Value="UserMasterVM.GenderId">

                            @foreach (var state in UserMasterVM.ListofGender)
                            {
                                <option value="@state.Value">@state.Text</option>
                            }
                        </InputSelect>
                        <ValidationMessage For="@(() => UserMasterVM.GenderId)" />
                    </div>
                    <div class="form-group col-md-4">
                        <label for="Address">Status: </label>
                        <InputCheckbox @bind-Value="@UserMasterVM.Status"></InputCheckbox>
                        <ValidationMessage class="text-danger" For="@(() => UserMasterVM.Status)" />
                    </div>

                </div>
            </div>
            <div class="card-footer">
                <button type="submit" id="btnsubmit" class="btn btn-success">Submit</button>
                <a class="btn btn-danger" href="">Clear</a>
                <a class="btn btn-primary" href="/UserGrid">List</a>
            </div>
        </div>
    </EditForm>
</div>

EditUserComponentBase Class Source Code

using System;
using System.Collections.Generic;
using BlazorPlayGround.Data.UserMasters.Command;
using BlazorPlayGround.Data.UserMasters.Queries;
using BlazorPlayGround.Model;
using BlazorPlayGround.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.JSInterop;

namespace BlazorPlayGround2.Pages
{
    public class EditUserComponentBase : ComponentBase
    {
        [Inject] public IJSRuntime JsRuntime { get; set; }
        [Inject] private IUserMasterQueries UserMasterQueries { get; set; }
        [Inject] private IUserMasterCommand UserMasterCommand { get; set; }
        [Inject] NavigationManager NavManager { get; set; }
        public UserMasterEditViewModel UserMasterVM { get; set; } = new UserMasterEditViewModel();
        [Parameter] public int Id { get; set; }

        protected override void OnInitialized()
        {
            UserMasterVM = UserMasterQueries.GetUserDetailsforEdit(Id);
            UserMasterVM.ListofGender =  new List<SelectListItem>()
            {
                new SelectListItem()
                {
                    Text="Select",
                    Value =""
                },
                new SelectListItem()
                {
                    Text="Male",
                    Value ="1"
                },
                new SelectListItem()
                {
                    Text="Female",
                    Value ="2"
                }
            };
        }


        protected async void FormSubmitted()
        {
            bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure you Want to Update User Details?"); 
            if (confirmed)
            {

                var userMaster = new UserMasterModel()
                {
                    Address = UserMasterVM.Address,
                    EmailId = UserMasterVM.EmailId,
                    FirstName = UserMasterVM.FirstName,
                    GenderId = Convert.ToInt32(UserMasterVM.GenderId),
                    LastName = UserMasterVM.LastName,
                    MiddleName = UserMasterVM.MiddleName,
                    MobileNo = UserMasterVM.MobileNo,
                    Status = UserMasterVM.Status,
                    UserId = UserMasterVM.UserId,

                };

                UserMasterCommand.Update(userMaster);
                NavManager.NavigateTo("UserGrid", false);

            }
            else
            {
                await JsRuntime.InvokeVoidAsync("showAlert", "Cancel");
            }
        }
    }
}

Now Let’s run the application and access /UserGrid Page.

Next, to edit data, just click on the Edit button. It will redirect to the EditUser form with UserId in the URL.

Below is Edit Screen

In edit form, we are going to edit Mobile no to 8888888888.

After clicking on submit, it will ask for confirmation, update data and redirect to UserGrid Page.

Exit mobile version