Hi,
I need to pass the object from Register.cshtml & Register.cshtml.cs to Registerform.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;
using System.Threading.Tasks;
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; } = new OtpRegisterVm();
public bool IsPhoneNumberPresent { get; set; }
public bool IsPhoneNumberValidated { get; set; }
public bool OtpProcessing { get; set; }
public bool Processing { get; set; }
public string GeneratedOTP { get; set; }
public void OnGet(string loginPhoneNumber)
{
IsPhoneNumberPresent = !string.IsNullOrEmpty(loginPhoneNumber);
}
public async Task<IActionResult> OnPostGenerateRegisterOtpAsync()
{
OtpProcessing = true;
if (string.IsNullOrEmpty(LoginModel.Username))
{
Notify.Add(TempData, false, "", "Phone Number required");
OtpProcessing = false;
return Page();
}
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)
{
GeneratedOTP = response.Content;
Notify.Add(TempData, true, $"OTP Generated successfully: {GeneratedOTP}", "");
}
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;
Processing = false;
return RedirectToPage("/Auth/RegisterForm");
}
else
{
Notify.Add(TempData, false, "", response.Message);
}
Processing = false;
return Page();
}
}
}
[BindProperty]
public OtpRegisterVm LoginModel { get; set; } = new OtpRegisterVm(); input field data are storing here from Register.cshtml
That data needs to be passed to the below code:
RegisterForm.cshtml
<div class="container">
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card">
<div class="card-body">
<form method="post" asp-page-handler="ValidSubmit" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="RegisterVmModel.FirstName"></label>
<input asp-for="RegisterVmModel.FirstName" class="form-control" autocomplete="off" />
<span asp-validation-for="RegisterVmModel.FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="RegisterVmModel.LastName"></label>
<input asp-for="RegisterVmModel.LastName" class="form-control" autocomplete="off" />
<span asp-validation-for="RegisterVmModel.LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="RegisterVmModel.EmployeeId"></label>
<input asp-for="RegisterVmModel.EmployeeId" class="form-control" autocomplete="off" />
<span asp-validation-for="RegisterVmModel.EmployeeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="RegisterVmModel.Enterprise">Enterprise Name:</label>
<input asp-for="RegisterVmModel.Enterprise" class="form-control" autocomplete="off" />
<!-- Add validation message if needed -->
<span asp-validation-for="RegisterVmModel.Enterprise" class="text-danger"></span>
@*
@foreach (var enterprise in Model.SearchEnterprise(Model.Enterprise).Result)
{
<div>@enterprise</div>
} *@
</div>
<div class="form-group">
<label asp-for="RegisterVmModel.Password"></label>
<input asp-for="RegisterVmModel.Password" class="form-control" autocomplete="off" type="password" />
<span asp-validation-for="RegisterVmModel.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="RegisterVmModel.ConfirmPassword"></label>
<input asp-for="RegisterVmModel.ConfirmPassword" class="form-control" autocomplete="off" type="password" />
<span asp-validation-for="RegisterVmModel.ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Photo"></label>
<input type="file" id="photoInput" name="Photo" class="form-control" />
<span asp-validation-for="Photo" class="text-danger"></span>
</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-outline-primary btn-sm">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Here we are not providiing input for Username BUT we need to fetch it from Register Bind PROPRTY
Register.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 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;
public bool EnterpriseError { get; set; } = false;
public bool IsPhoneNumberValidated { get; set; } = false;
[BindProperty]
public IFormFile Photo { get; set; }
//public IActionResult OnGet()
//{
// // Initialize RegisterVmModel if it's null
// 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 void OnGet()
{
if (RegisterVmModel == null)
{
RegisterVmModel = new RegisterVm();
}
if (LoginModel == null)
{
LoginModel = new OtpRegisterVm();
}
}
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);
}
}
} *********
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;
}
Here the Username = LoginModel.CountryCode + LoginModel.Username is null even after checking with break point
ViewModels
using System.ComponentModel.DataAnnotations;
namespace AuthenticationDemo.ViewModels
{
public class OtpRegisterVm
{
[MinLength(10, ErrorMessage = "Phone Number must be have 10 or more digits")]
[MaxLength(15, ErrorMessage = "Phone Number is too large")]
[RegularExpression(@"^[0-9]+$", ErrorMessage = "Invalid Phone Number")]
//[RegularExpression(@"^\+[0-9]+$", ErrorMessage = "Phone Number must contain Country code")]
public string Username { get; set; }
[Required(ErrorMessage = "OTP is Required. Use 'Generate OTP'")]
public string Password { get; set; }
public string CountryCode { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace AuthenticationDemo.ViewModels
{
public class RegisterVm
{
[Required(ErrorMessage = "First Name is Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is Required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Employee ID is Required")]
public string EmployeeId { get; set; }
[MinLength(2, ErrorMessage = "Enterprise must be more than 2 letters")]
public string Enterprise { get; set; }
[Required(ErrorMessage = "Password is Required")]
[MinLength(6, ErrorMessage = "Password must be more than 5 letters")]
public string Password { get; set; }
[Required(ErrorMessage = "Confirm Password is Required")]
[Compare(nameof(Password), ErrorMessage = "Password does'nt match")]
public string ConfirmPassword { get; set; }
}
}