How to pass the input data from one page to another

Surya Chandra Mohan 20 Reputation points
2024-05-16T05:34:41.9466667+00:00
Register.cshtml.cs

using FaceAdminApp.Auth;
using FaceAdminApp.DTOs;
using FaceAdminApp.Models;
using FaceAdminApp.Services;
using FaceAdminApp.Utilities;
using FaceAdminApp.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace FaceAdminApp.Pages.Auth
{
    public class RegisterModel : PageModel
    {
        private readonly ILoginService _loginService;
        private readonly VacApiService _apiService;
        public RegisterModel(ILoginService loginService, VacApiService apiService)
        {
            _loginService = loginService;
            _apiService = apiService;
        }
        [BindProperty]
        public string LoginPhoneNumber { get; set; }
        [BindProperty]
        public string CountryCode { get; set; }
        [BindProperty]
        public OtpRegisterVm LoginModel { get; set; }
        public bool IsPhoneNumberPresent { get; set; } = false;
        public bool IsPhoneNumberValidated { get; set; }
        public bool OtpProcessing { get; set; }
        public bool Processing { get; set; }
        //public void OnGet()
        //{
        //    if (!string.IsNullOrEmpty(LoginPhoneNumber))
        //    {
        //        IsPhoneNumberPresent = true;
        //        LoginModel = new OtpRegisterVm { Username = LoginPhoneNumber, CountryCode = CountryCode };
        //    }
        //    else
        //    {
        //        IsPhoneNumberPresent = false;
        //    }
        //}
        public void OnGet()
        {
            if (!string.IsNullOrEmpty(LoginPhoneNumber))
            {
                IsPhoneNumberPresent = true;
                LoginModel = new OtpRegisterVm { Username = LoginPhoneNumber, CountryCode = CountryCode };
            }
            else
            {
                IsPhoneNumberPresent = false;
            }
        }
        public async Task<IActionResult> OnPostGenerateOtpAsync()
        {
            OtpProcessing = true;
            if (LoginModel == null || string.IsNullOrEmpty(LoginModel.Username))
            {
                Notify.Add(TempData, false, "", "Phone Number required");
                OtpProcessing = false;
                return Page();
            }
            else if (LoginModel.Username.Length < 10)
            {
                Notify.Add(TempData, false, "", "Enter valid Phone Number");
                OtpProcessing = false;
                return Page();
            }
            //Notify.Add(TempData, true, $"OTP Generated successfully: {generatedOtp}", "");
            var dto = new PhoneNumberDto { PhoneNumber = LoginModel.CountryCode + LoginModel.Username };
            var response = await _apiService.GenerateRegisterOtp(dto);
            if (response.IsSuccess)
            {
                Notify.Add(TempData, true, "OTP Generated successfully", "");
            }
            else
            {
                Notify.Add(TempData, false, "", response.Message);
            }
            OtpProcessing = false;
            return Page();
        }
        public async Task<IActionResult> OnPostAsync()
        {
            Processing = true;
            if (string.IsNullOrEmpty(LoginModel.Username) || string.IsNullOrEmpty(LoginModel.Password))
            {
                Notify.Add(TempData, false, "", "Phone Number and OTP are required");
                Processing = false;
                return Page();
            }
            if (LoginModel.Username.Length < 10 || LoginModel.Password.Length != 6)
            {
                Notify.Add(TempData, false, "", "Invalid Phone Number or OTP");
                Processing = false;
                return Page();
            }
            var dto = new LoginDto { Username = LoginModel.CountryCode + LoginModel.Username, Password = LoginModel.Password };
            var response = await _apiService.ValidateRegisterOtp(dto);
            if (response.IsSuccess)
            {
                Notify.Add(TempData, true, "Phone number validated", "");
                IsPhoneNumberValidated = true;
            }
            else
            {
                Notify.Add(TempData, false, "", response.Message);
            }
            Processing = false;
            return RedirectToPage("/Auth/RegistrationForm");
        }
    }
}

RegistrationForm.cshtml.cs


using FaceAdminApp.Auth;
using FaceAdminApp.DTOs;
using FaceAdminApp.Services;
using FaceAdminApp.Utilities;
using FaceAdminApp.ViewModels;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text;
namespace FaceAdminApp.Pages.Auth
{
    public class RegistrationFormModel : PageModel
    {
        private readonly VacApiService _apiService;
        private readonly ILoginService _loginService;
        private readonly NavigationManager _navManager;
        private readonly DialogService _dialogService;
        public RegistrationFormModel(VacApiService apiService, ILoginService loginService, NavigationManager navManager, DialogService dialogService)
        {
            _apiService = apiService;
            _loginService = loginService;
            _navManager = navManager;
            _dialogService = dialogService;
            SelectListDto = new SelectListDto();
            RegisterVmModel = new RegisterVm();
            LoginModel = new OtpRegisterVm();
        }
        [BindProperty]
        public RegisterVm RegisterVmModel { get; set; }
        public OtpRegisterVm LoginModel { get; set; }
        [BindProperty]
        public int StepOffset { get; set; } = 0;
        public string Enterprise { get; set; }
        //public SelectListDto SelectListDto = new();
        public SelectListDto SelectListDto { get; set; }
        public List<string> Enterprises = new List<string>();
        public LoginResultDto response;
        public bool Processing = false;
        [BindProperty]
        public bool OtpProcessing { get; set; } = false;
        public bool EnterpriseError = false;
        public bool IsPhoneNumberValidated = false;
        [BindProperty]
        public IFormFile Photo { get; set; }
        public async Task<IActionResult> OnPostValidSubmit()
        {
            Processing = true;
            if (!ModelState.IsValid)
            {
                return Page();
            }
            var dto = await MapVmToDto();
            if (Photo != null && Photo.Length > 0)
            {
                if (!IsImageFile(Photo.FileName))
                {
                    Notify.Add(TempData, false, "Please upload a valid image file.", "");
                    Processing = false;
                    return Page();
                }
                // Save the file to a location or process it
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", Photo.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await Photo.CopyToAsync(stream);
                }
                // Attach the file path to your DTO
                dto.PhotoPath = filePath;
            }
            var response = await _apiService.RegisterUser(dto);
            if (response.Succeeded)
            {
                Notify.Add(TempData, false, "Registration was successful.", "");
            }
            else
            {
                Notify.Add(TempData, false, response.Error, "");
                Processing = false;
            }
            return Page();
        }
        public bool IsImageFile(string fileName)
        {
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return allowedExtensions.Contains(extension);
        }
        public async Task<RegisterDto> MapVmToDto()
        {
            var item = SelectListDto.SelectList.FirstOrDefault(e =>
                e.Name.Equals(RegisterVmModel.Enterprise, StringComparison.OrdinalIgnoreCase));
            var enterpriseId = item is null ? 0 : item.Id;
            var dto = new RegisterDto
            {
                FirstName = RegisterVmModel.FirstName,
                LastName = RegisterVmModel.LastName,
                UserName = LoginModel.CountryCode + LoginModel.Username,
                EnterpriseId = enterpriseId,
                EmployeeId = RegisterVmModel.EmployeeId,
                Password = RegisterVmModel.Password,
            };
            return dto;
        }
        public async Task OnValidPhoneNumberSubmit()
        {
            Processing = true;
            if (LoginModel.Username.Length < 10 || LoginModel.Password.Length != 6)
            {
                Notify.Add(TempData, false, $"Invalid Phone Number or OTP", "");
                Processing = false;
                return;
            }
            var dto = new LoginDto { Username = LoginModel.CountryCode + LoginModel.Username, Password = LoginModel.Password };
            var response = await _apiService.ValidateRegisterOtp(dto);
            if (response.IsSuccess)
            {
                Notify.Add(TempData, true, $"Phone number validated", "");
                IsPhoneNumberValidated = true;
            }
            else
            {
                Notify.Add(TempData, false, $"{response.Message}", "");
            }
            Processing = false;
        }
        public string ValidateEnterprise(string input)
        {
            if (!Enterprises.Contains(input))
            {
                return "Only registered enterprises allowed";
            }
            return null;
        }
        public async Task<IEnumerable<string>> SearchEnterprise(string value)
        {
            if (string.IsNullOrEmpty(value) || value.Length < 3)
                return Enumerable.Empty<string>();
            return await Task.FromResult(Enterprises.Where(x => x.StartsWith(value, StringComparison.InvariantCultureIgnoreCase)));
        }
    }
}

In the register.cshtml.cs page input fields are fetching input data to bindproperty of otpregsiterVm and otp generation and validation methods are working in this page. Pass this data to registrationform page of mapvmdto method of USERNAME PROPERTY of registerdto(

UserName = LoginModel.CountryCode + LoginModel.Username,

) to register user with required input fields to the otp generated username

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,253 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JasonPan - MSFT 4,626 Reputation points Microsoft Vendor
    2024-05-16T08:55:46.5333333+00:00

    Hi @Surya Chandra Mohan,

    Could kindly have a look this thread (How to pass input data from one page to another page property)?

    I am using handler to pass the object. You can give it a try.

    Best Regards

    Jason

    0 comments No comments