How to pass input data from one page to another page property

Nandhini S 0 Reputation points
2024-05-16T05:50:59.9633333+00:00
Register.cshtml
<form method="post">
    <div class="mb-3 row">
        <div class="col-md-4">
            <label for="CountryCode" class="form-label">Country Code</label>
            <select class="form-select" id="CountryCode" asp-for="LoginModel.CountryCode">
                <option value="+91">+91</option>
                <option value="+49">+49</option>
                <option value="+1">+1</option>
                <option value="+33">+33</option>
            </select>
        </div>
        <div class="col-md-6">
            <label for="PhoneNumber" class="form-label">Mobile Number</label>
            <input type="text" class="form-control" id="PhoneNumber" asp-for="LoginModel.Username">
        </div>
    </div>
    <div class="mb-3 row">
        <div class="col-md-6">
            <label for="OTP" class="form-label">OTP</label>
            <input id="OTP" type="text" class="form-control" asp-for="LoginModel.Password" autocomplete="off" />
        </div>
        <div class="col-md-4 d-flex align-items-end">
                <button type="submit" class="btn btn-light mt-md-4"  asp-page-handler="GenerateRegisterOtp" disabled="@Model.OtpProcessing">
                    @if (Model.OtpProcessing)
                    {
                        <div class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></div>
                        <span>GENERATING</span>
                    }
                    else
                    {
                        <span>GENERATE OTP</span>
                    }
                </button>
        </div>
    </div>
        <div class="form-group d-flex justify-content-between">
            <a asp-page="/Auth/Login" class="btn btn-success mx-2">LOGIN</a>
            <button type="submit" class="btn btn-danger" asp-page-handler="ValidPhoneNumberSubmit" disabled="@Model.Processing">
                @if (Model.Processing)
                {
                    <div class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></div>
                    <span>VALIDATING</span>
                }
                else
                {
                    <span>VALIDATE</span>
                }
            </button>
        </div>
</form>
Register.cshtml.cs

using AuthenticationDemo.Auth;
using AuthenticationDemo.DTOs;
using AuthenticationDemo.Services;
using AuthenticationDemo.Utilities;
using AuthenticationDemo.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AuthenticationDemo.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; } = false;
        public bool OtpProcessing { get; set; }
        public bool Processing { get; set; }
        public string GeneratedOTP { get; set; }
        public void OnGet(string LoginPhoneNumber)
        {
            if (!string.IsNullOrEmpty(LoginPhoneNumber))
            {
                IsPhoneNumberPresent = true;
            }
            else
            {
                IsPhoneNumberPresent = false;
            }
        }
        public async Task<IActionResult> OnPostGenerateRegisterOtpAsync()
        {
            OtpProcessing = true;
            if (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();
            }
            var dto = new PhoneNumberDto { PhoneNumber = LoginModel.CountryCode + LoginModel.Username };
            var response = await _apiService.GenerateRegisterOtp(dto);
            if (response.IsSuccess)
            {
                string otp = response.Content;
                GeneratedOTP = otp; // Set the generated OTP value
                Notify.Add(TempData, true, $"OTP Generated successfully: {otp}", "");
            }
            else
            {
                Notify.Add(TempData, false, "", response.Message);
            }
            OtpProcessing = false;
            return Page();
        }
        public async Task<IActionResult> OnPostValidPhoneNumberSubmitAsync()
        {
            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/RegisterForm");
        }
    }
}


In this page otp genartion and validation method are working for the defined proprty and data are storing in this

[BindProperty] public OtpRegisterVm LoginModel { get; set; }




RegisterForm.cshtml.cs
using AuthenticationDemo.Auth;
using AuthenticationDemo.DTOs;
using AuthenticationDemo.Services;
using AuthenticationDemo.Utilities;
using AuthenticationDemo.ViewModels;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text;
namespace AuthenticationDemo.Pages.Auth
{
    public class RegisterFormModel : PageModel
    {
        private readonly VacApiService _apiService;
        private readonly ILoginService _loginService;
        private readonly NavigationManager _navManager;
        public RegisterFormModel(VacApiService apiService, ILoginService loginService, NavigationManager navManager)
        {
            _apiService = apiService;
            _loginService = loginService;
            _navManager = navManager;
      
        }
        [BindProperty]
        public RegisterVm RegisterVmModel { get; set; }
        public string CountryCode { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public OtpRegisterVm LoginModel { get; set; }
        public SelectListDto SelectListDto { get; set; } = new();
        public List<string> Enterprises = new List<string>();
        public LoginResultDto response { get; set; }
        public bool Processing { get; set; } = false;
        [BindProperty]
        public bool OtpProcessing { get; set; } = false;
        public bool EnterpriseError { get; set; } = false;
        public bool IsPhoneNumberValidated { get; set; } = false;
        [BindProperty]
        public IFormFile Photo { get; set; }
        public IActionResult OnGet()
        {
      
            if (RegisterVmModel == null)
            {
                RegisterVmModel = new RegisterVm();
            }
            if (LoginModel == null)
            {
                LoginModel = new OtpRegisterVm();
            }
        
            // SelectListDto = await _apiService.GetAllEnterprisesAsList();
            //Enterprises = SelectListDto.SelectList.Select(n => n.Name).ToList();
            return Page();
        }
        public async Task<IActionResult> OnPostValidSubmit()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            Processing = true;
            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();
                }
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", Photo.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await Photo.CopyToAsync(stream);
                }
            }
            var response = await _apiService.RegisterUser(dto);
            if (response.Succeeded)
            {
                Notify.Add(TempData, true, "Registration was successful.", "");
            }
            else
            {
                Notify.Add(TempData, false, $"Failed to register: {response.Error}", "");
                Processing = false;
            }
            return Page();
        }
        private 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 bool IsImageFile(string fileName)
        {
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return allowedExtensions.Contains(extension);
        }
    }
}


I am trying access Countrycode and username data from the loginmodel of otpregistervmafter otp genearted and validated . how to pass that data to

UserName = LoginModel.CountryCode + LoginModel.Username,

this propty to register user to database.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,254 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:47:49.5033333+00:00

    Hi @Nandhini S,

    According to your needs, I create a custom model(DataModel inside the Model Folders), and pass it from Index Page to Another Page by using handler.

    Here is the detailed steps for you.

    Index.cshtml

    @page
    @model IndexModel
    @using WebApplication1.Model
    @{
        ViewData["Title"] = "Home page";
    }
    <div class="text-center">
        <form method="post" asp-page="/Auth/RegisterForm" asp-page-handler="ReceiveMessage">
            <input asp-for="Data.Id" class="form-control" />
            <input asp-for="Data.Name" class="form-control" />
            <button type="submit" class="btn btn-primary">Send Model to Page RegisterForm</button>
        </form>
    </div>
    

    Index.cshtml.cs

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using WebApplication1.Model;
    namespace WebApplication1.Pages
    {
        public class IndexModel : PageModel
        {
            [BindProperty]
            public DataModel Data { get; set; } = new DataModel();
            private readonly ILogger<IndexModel> _logger;
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
            public void OnGet()
            {
            }
           
        }
    }
    

    RegisterForm.cshtml

    @page 
    @model WebApplication1.Pages.Auth.RegisterFormModel
    <h2>Data from Page Index:</h2>
    <p>@Model.Id</p>
    <p>@Model.Name</p>
    @{
    }
    

    RegisterForm.cshtml.cs

    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using WebApplication1.Model;
    namespace WebApplication1.Pages.Auth
    {
        public class RegisterFormModel : PageModel
        {
            public string? Id { get; set; }
            public string? Name { get; set; }
            public void OnGet()
            {  
            }
            public void OnPostReceiveMessage([FromForm] DataModel Data)
            {
                Id = Data.Id;
                Name = Data.Name;
            }
        }
    }
    

    DataModel.cs

    namespace WebApplication1.Model
    {
        public class DataModel
        {
            public string? Id { get; set; }
            public string? Name { get; set; }
        }
    }
    

    My Sample Project

    User's image

    Test Result

    User's image

    User's image

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Jason