hi I am new in EF core Razor pages .and I am using Code First Approach .So I want to implement Male Female Radio Button Property .I generated The migration Adding Property But I Am not Understanding How to Get That Values In Razor Page. My ApplicationUser.cs Class
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmployeCode { get; set; }
public string Designation { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateOfJoining { get; set; }
public string EmergencyNo { get; set; }
public string AdharNo { get; set; }
//Department dropdown and city and country thing
public string Gender { get; set; }
public string[] Genders = new[] { "Male", "Female", };
public string Country { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
I added Gender Here.Then Added Migration.
My RegisterModel class
//[AllowAnonymous]
//[Authorize(Roles = StaticDetails.AdminEndUser)]
public class RegisterModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
////comented the Iemailsender because its causing error.
// private readonly IEmailSender _emailSender;
//// added by me for dependency injection;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _db;
public RegisterModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<RegisterModel> logger,
// IEmailSender emailSender,
////added by me for constructor for the upper used dependency injection;
RoleManager<IdentityRole> roleManager,
ApplicationDbContext db)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
// _emailSender = emailSender;
////added by me for upper used constructor;
_roleManager = roleManager;
_db = db;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
//added by me
//[BindProperty]
//public string Gender { get; set; }
//public string[] Genders = new[] { "Male", "Female", "Unspecified" };
//[DataType(DataType.Date)]
//[Column(TypeName = "Date")]
//public DateTime DateOfBirth { get; set; }
[Required]
[RegularExpression("([a-zA-Z][a-zA-Z ] )", ErrorMessage = "Only alphabets are allowed")]
//public string FullName { get; set; }
public string FirstName { get; set; }
[RegularExpression("([a-zA-Z][a-zA-Z ] )", ErrorMessage = "Only alphabets are allowed")]
public string LastName { get; set; }
[Required]
[RegularExpression("(^.*$)", ErrorMessage = "Invalid EmployeCode")]
public string EmployeCode { get; set; }
public string Designation { get; set; }
//[DataType(DataType.Date)]
//[Column(TypeName = "Date")]
[Required]
[BindProperty]
public DateTime DateOfBirth { get; set; }
[Required]
[BindProperty]
public DateTime DateOfJoining { get; set; }
[Required]
[Display(Name = "Emergency No")]
[MaxLength(10), MinLength(10)]
public string EmergencyNo { get; set; }
[Required]
[MaxLength(12),MinLength(12)]
public string AdharNo { get; set; }
[Required]
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
[Required]
[Display(Name = "Phone Number")]
[MaxLength(10)/*, MinLength(10)*/]
public string PhoneNumber { get; set; }
[Required]
[BindProperty]
public string Gender { get; set; }
public string[] Genders = new[] { "Male", "Female", };
}
public class MobileUniqueAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var _context = (ApplicationDbContext)validationContext.GetService(typeof(ApplicationDbContext));
var entity = _context.ApplicationUser.SingleOrDefault(e => e.PhoneNumber == value.ToString());
if (entity != null)
{
return new ValidationResult(/*GetErrorMessage(value.ToString())*/"Hey The MobileNo is Alrdy Present");
}
return ValidationResult.Success;
}
public string GetErrorMessage(string mobile)
{
return $"Mobile {mobile} is already in use.";
}
//ValidationResult validphone = IsValid(object value, ValidationContext validationContext);
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
//var _context = (ApplicationDbContext)_db.ApplicationUser(typeof(ApplicationDbContext));
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
//// var user = new Identityuser { UserName = Input.Email, Email = Input.Email };...I edited it because in Applicationuser class i am putting the name,address,city,postal code.
var user = new ApplicationUser
{
UserName = Input.Email,
Email = Input.Email,
FirstName = Input.FirstName,
LastName = Input.LastName,
EmployeCode = Input.EmployeCode,
Designation = Input.Designation,
//DateOfBirth= Convert.ToDateTime("DateOfBirth"),
DateOfBirth = Input.DateOfBirth,
DateOfJoining = Input.DateOfJoining,
EmergencyNo = Input.EmergencyNo,
AdharNo = Input.AdharNo,
Address = Input.Address,
City = Input.City,
PostalCode = Input.PostalCode,
PhoneNumber = Input.PhoneNumber,
Gender = Input.Gender,
Genders = Input.Genders
};
////after dependency injection we come to after post handler.and in below line they r creating the user.
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
////added by me if this is successful we want chk if role exits in the detabase.
////if admin user doesnot exits we want to creat it.
////StaticDetails class SD created by me.
if (!await _roleManager.RoleExistsAsync(StaticDetails.AdminEndUser))
{
await _roleManager.CreateAsync(new IdentityRole(StaticDetails.AdminEndUser));
}
if (!await _roleManager.RoleExistsAsync(StaticDetails.HrEndUser))
{
await _roleManager.CreateAsync(new IdentityRole(StaticDetails.HrEndUser));
}
if (!await _roleManager.RoleExistsAsync(StaticDetails.ItEndUser))
{
await _roleManager.CreateAsync(new IdentityRole(StaticDetails.ItEndUser));
}
if (!await _roleManager.RoleExistsAsync(StaticDetails.EmployeeEndUser))
{
await _roleManager.CreateAsync(new IdentityRole(StaticDetails.EmployeeEndUser));
}
////roles are created now have to assign it to a user.
////adminuser for now.means when i will creat it will by default take adminuser.
await _userManager.AddToRoleAsync(user, StaticDetails.EmployeeEndUser);
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
// await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
// $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
My Register.cshtml class
@page
@model RegisterModel
@{
ViewData["Title"] = "Register";
}
@*<h1>@ViewData["Title"]</h1>*@
<h2 >Create a new account</h2>
<div >
<div >
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div asp-validation-summary="All" ></div>
<div >
<div >
<div >
<label asp-for="Input.FirstName"></label>
</div>
<div >
<input asp-for="Input.FirstName" />
</div>
<span asp-validation-for="Input.FirstName" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.LastName"></label>
</div>
<div >
<input asp-for="Input.FirstName" />
</div>
<span asp-validation-for="Input.FirstName" ></span>
</div>
</div>
@foreach (var gender in Model.ReturnUrl.Genders)
{
@Html.RadioButtonFor(model => model.Gender, gender) @gender<br />
}
<div >
<div >
<div >
<label asp-for="Input.EmployeCode"></label>
</div>
<div >
<input asp-for="Input.EmployeCode" />
</div>
<span asp-validation-for="Input.EmployeCode" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.Designation"></label>
</div>
<div >
<input asp-for="Input.Designation" />
</div>
<span asp-validation-for="Input.Designation" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.DateOfBirth"></label>
</div>
<div >
<input asp-for="Input.DateOfBirth" />
</div>
<span asp-validation-for="Input.DateOfBirth" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.DateOfJoining"></label>
</div>
<div >
<input asp-for="Input.DateOfJoining" />
</div>
<span asp-validation-for="Input.DateOfJoining" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.Email"></label>
</div>
<div >
<input asp-for="Input.Email" />
</div>
<span asp-validation-for="Input.Email" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.PhoneNumber"></label>
</div>
<div >
<input asp-for="Input.PhoneNumber" />
</div>
<span asp-validation-for="Input.PhoneNumber" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.EmergencyNo"></label>
</div>
<div >
<input asp-for="Input.EmergencyNo" />
</div>
<span asp-validation-for="Input.EmergencyNo" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.AdharNo"></label>
</div>
<div >
<input asp-for="Input.AdharNo" />
</div>
<span asp-validation-for="Input.AdharNo" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.Address"></label>
</div>
<div >
<input asp-for="Input.Address" />
</div>
<span asp-validation-for="Input.Address" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.City"></label>
</div>
<div >
<input asp-for="Input.City" />
</div>
<span asp-validation-for="Input.City" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.PostalCode"></label>
</div>
<div >
<input asp-for="Input.PostalCode" />
</div>
<span asp-validation-for="Input.PostalCode" ></span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.Password"></label>
</div>
<div >
<input asp-for="Input.Password" />
</div>
<span asp-validation-for="Input.Password" >.The Password must be at least 6 and at max 100 characters long,atleast one alpha numeric char and contain atleast one uppercase(A-Z).</span>
</div>
</div>
<div >
<div >
<div >
<label asp-for="Input.ConfirmPassword"></label>
</div>
<div >
<input asp-for="Input.ConfirmPassword" />
</div>
<span asp-validation-for="Input.ConfirmPassword" ></span>
</div>
</div>
<div >
<div >
<div >
</div>
<div >
<button type="submit" >Register </button>
</div>
</div>
</div>
</form>
</div>
</div>
@*<div >
<div >
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" ></div>
<div >
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" />
<span asp-validation-for="Input.Email" ></span>
</div>
<div >
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" />
<span asp-validation-for="Input.Password" ></span>
</div>
<div >
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" />
<span asp-validation-for="Input.ConfirmPassword" ></span>
</div>
<button type="submit" >Register</button>
</form>
</div>*@
@*<div >
<section>
<h4>Use another service to register.</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
for details on setting up this ASP.NET application to support logging in via external services.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" >
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>*@
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
My problem is Did i operated The right way.in That Case How To Get That Genders List.
CodePudding user response:
public class RegisterModel : PageModel { ... [BindProperty] public InputModel Input { get; set; } public class InputModel { ... [Required] [BindProperty] public string Gender { get; set; } public string[] Genders = new[] { "Male", "Female", }; } ... }
From the above code, we can see you are using the InputModel to bind the property and the Genders/Gender, so, in the OnGetAsync method, we need to create the Input model instance, to prevent the Input model NullReferenceException. Code like this:
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
Input = new InputModel();
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
Then, when displaying the radio button in the view page, the code should be like this: access the Genders via the Input, and set the selected value using the Input.Gender.
@foreach (var gender in Model.Input.Genders)
{
@Html.RadioButtonFor(model => model.Input.Gender, gender) @gender<br />
}
After that, the result is like this: we can get the selected gender via the Input.Gender
property.