How To Populate A dropdown feature In Ef core razor pages

Arnab 66 Reputation points
2022-06-27T08:56:12.887+00:00

hi , I made a department class.. And I have also A ApplicationUser class responsible for registering a user. While Registering a User I want A department Dropdown Feature Should be Populated From Database . I am new in this field so can Anyone suggest How to implement That.
Classes are
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; }  
        //added.  
  
        public int DepartmentId { get; set; }  
        public Department Department { get; set; }  
  
    }  

Department.cs class

 public class Department  
    {  
       [Key]  
        public int Id { get; set; }  
  
        [Required]  
        public string Name { get; set; }  
  
        public string Description { get; set; }  
  
        public ICollection<ApplicationUser> ApplicationUsers { get; set; }  
    }  

Register.cshtml.cs Model class

  //[AllowAnonymous]  
    //[Authorize(Roles = StaticDetails.AdminEndUser)]  
    [BindProperties]  
    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 IQueryable<SelectListItem> CategoryList { get; private 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; }  
            
            public IEnumerable<SelectListItem> CategoryList { 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]  
            [DataType(DataType.Date)]  
            public DateTime DateOfBirth { get; set; }  
            [Required]  
            [BindProperty]  
            [DataType(DataType.Date)]  
            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; }  
  
            [Required]  
            public string City { get; set; }  
  
            [Required]  
            public string Country { 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", };  
  
            List<Department> options { get; set; }  
             [BindProperty]  
           public Department Department { get; set; }  
        }  
        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)  
        {  
            CategoryList = _db.Department.Select(i => new SelectListItem()  
            {  
                Text = i.Name,  
                Value =i.Id.ToString()  
            });  
            ReturnUrl = returnUrl;  
            Input = new InputModel();  
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();  
              
        }  
  
  
            public async Task<IActionResult> OnPostAsync(string returnUrl = null)  
            {  
            //var submitdata = Input; This line is for Debug.    
                //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,  
                    Country = Input.Country,  
                    City = Input.City,  
                    PostalCode = Input.PostalCode,  
                    PhoneNumber = Input.PhoneNumber,  
                    Gender = Input.Gender,  
                    Genders = Input.Genders,  
                    Department = Input.Department  
  
                    };  
  
                
                ////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();  
              
        }  
}  

Register.cshtml class

@page  
@model RegisterModel  
  
@{  
    ViewData["Title"] = "Register";  
}  
  
@*<h1>@ViewData["Title"]</h1>*@  
  
<h2 class="text-info pt-2 pb-3">Create a new account</h2>  
<div class="row bg-white border">  
    <div class="col-md-8">  
        <form asp-route-returnUrl="@Model.ReturnUrl" method="post">  
            <div asp-validation-summary="All" class="text-danger"></div>  
  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.FirstName"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.FirstName" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.FirstName" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.LastName"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.FirstName" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.FirstName" class="text-danger"></span>  
                </div>  
            </div>  
  
            @*<div class="form-check">  
                <label class="form-check-label">  
                    <input type="radio" class="form-check-input" name="optradio">Option 1  
                </label>  
            </div>  
            <div class="form-check">  
                <label class="form-check-label">  
                    <input type="radio" class="form-check-input" name="optradio">Option 2  
                </label>  
            </div>  
            <div class="form-check disabled">  
                <label class="form-check-label">  
                    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3  
                </label>  
            </div>*@  
  
            <div class="form-check-inline">  
        <div class="col-12">  
            <label asp-for="Input.Gender"></label>  
        </div>  
  
        <div class="col-8">  
            @foreach (var gender in Model.Input.Genders)  
            {  
            @*@Html.RadioButtonFor(model => model.Input.Gender, gender) @gender<br />*@  
            <input type="radio" class="form-check-input" asp-for="Input.Gender" value="@gender" />@gender<br />  
            }  
        </div>  
        <span asp-validation-for="Input.Gender" class="text-danger"></span>  
    </div>  
  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.EmployeCode"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.EmployeCode" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.EmployeCode" class="text-info">.The EmployeCode must be at least 6 characters long,It Should Contain 'EST' In the bigining.EG. EST032</span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.Designation"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.Designation" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.Designation" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.DateOfBirth"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.DateOfBirth" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.DateOfBirth" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.DateOfJoining"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.DateOfJoining" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.DateOfJoining" class="text-danger"></span>  
                </div>  
            </div>  
  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.Email"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.Email" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.Email" class="text-danger"></span>  
                </div>  
  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.PhoneNumber"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.PhoneNumber" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.EmergencyNo"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.EmergencyNo" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.EmergencyNo" class="text-danger"></span>  
                </div>  
            </div>  
            @*<div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.AdharNo"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.AdharNo" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.AdharNo" class="text-danger"></span>  
                </div>  
            </div>*@  
  
            @*<div class="mb-3">  
                <lable asp-for="Model."></lable>  
  
            </div>*@  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.Country"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.Country" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.Country" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.Address"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.Address" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.Address" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.City"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.City" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.City" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.PostalCode"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.PostalCode" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.PostalCode" class="text-danger"></span>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label asp-for="Input.Password"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.Password" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.Password" class="text-info font-italic">.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 class="form-group">  
                <div class="row">  
  
                    <div class="col-4">  
                        <label asp-for="Input.ConfirmPassword"></label>  
                    </div>  
                    <div class="col-8">  
                        <input asp-for="Input.ConfirmPassword" class="form-control" />  
                    </div>  
                    <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>  
                </div>  
            </div>  
  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                    </div>  
                    <div class="col-8">  
                        <button type="submit" class="btn btn-success form-control">Register </button>  
  
                    </div>  
  
                </div>  
  
            </div>  
  
        </form>  
    </div>  
  
</div>  
  
@*<div class="row">  
    <div class="col-md-4">  
        <form asp-route-returnUrl="@Model.ReturnUrl" method="post">  
            <h4>Create a new account.</h4>  
            <hr />  
            <div asp-validation-summary="All" class="text-danger"></div>  
            <div class="form-group">  
                <label asp-for="Input.Email"></label>  
                <input asp-for="Input.Email" class="form-control" />  
                <span asp-validation-for="Input.Email" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <label asp-for="Input.Password"></label>  
                <input asp-for="Input.Password" class="form-control" />  
                <span asp-validation-for="Input.Password" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <label asp-for="Input.ConfirmPassword"></label>  
                <input asp-for="Input.ConfirmPassword" class="form-control" />  
                <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>  
            </div>  
            <button type="submit" class="btn btn-primary">Register</button>  
        </form>  
    </div>*@  
@*<div class="col-md-6 col-md-offset-2">  
                <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" class="form-horizontal">  
                                <div>  
                                    <p>  
                                        @foreach (var provider in Model.ExternalLogins)  
                                        {  
                                            <button type="submit" class="btn btn-primary" 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" />  
}  




  
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,188 questions
{count} votes

9 answers

Sort by: Most helpful
  1. Arnab 66 Reputation points
    2022-06-28T11:21:19.167+00:00

    @Zhi Lv - MSFT my Recent Register Model class
    //[AllowAnonymous]
    //[Authorize(Roles = StaticDetails.AdminEndUser)]
    [BindProperties]
    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; }  
      
            //[BindProperty]  
            //public int DepartmentId { set; get; }  
      
            public IEnumerable<SelectListItem> DepartmentList { get; private 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]  
                [DataType(DataType.Date)]  
                public DateTime DateOfBirth { get; set; }  
                [Required]  
                [BindProperty]  
                [DataType(DataType.Date)]  
                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; }  
      
                [Required]  
                public string City { get; set; }  
      
                [Required]  
                public string Country { 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", };  
      
                List<Department> options { get; set; }  
      
                  
                public IEnumerable<SelectListItem> DepartmentList { get; set; }  
      
                 
                public Department Department { get; set; }  
      
                public int DepartmentId { get; set; }  
                public SelectList DepartmentList1 { get; set; }  
                public List<SelectListItem> DepartmentItems { set; get; }  
            }  
             
            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)  
            {  
      
             DepartmentList = _db.Department.Select(i => new SelectListItem()  
                {  
                    Text = i.Name,  
                    Value = i.Id.ToString()  
                });  
                ReturnUrl = returnUrl;  
                Input = new InputModel();  
                 
      
                //DepartmentNameSL = await _db.Department.ToListAsync();  
      
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();  
                  
            }  
      
      
                public async Task<IActionResult> OnPostAsync(string returnUrl = null)  
                {  
                var submitdata = Input;/* This line is for Debug.*/    
                    //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,  
                        Country = Input.Country,  
                        City = Input.City,  
                        PostalCode = Input.PostalCode,  
                        PhoneNumber = Input.PhoneNumber,  
                        Gender = Input.Gender,  
                        Genders = Input.Genders,  
                        Department = Input.Department  
      
      
      
                        };  
      
                    
                    ////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();  
                  
            }  
        }  
    }  
    
    0 comments No comments

  2. Arnab 66 Reputation points
    2022-06-29T10:14:47.553+00:00

    @Zhi Lv - MSFT

    sir I tried that but was still getting the "name required " validation problem. then In Register.cshtml insted of Input.Department.Id i wrote Name

     <div class="col-8">  
                           <select name="Input.Department.Name" asp-items="Model.DepartmentList"></select>  
      </div>  
    

    now its saving . in my database in User's table its creating Department Id and also creating a new Department As well with that id in dbo.Department Table

    216030-qq.png

    in department Table
    216113-screenshot-2022-06-29-150847.jpg

    to resolve this i removed that Department = Input.Department while Creating a New ApplicationUser object.then i am getting this Exception

    216121-screenshot-2022-06-29-151856.jpg

    A lot of tanks to bear with me that far.

    0 comments No comments

  3. Arnab 66 Reputation points
    2022-07-05T12:14:47.103+00:00

    Thanks sir ....One more Thing Sir can you Walk Me through How to save Department While Editing The Application User Details
    My Edit.cshtml.cs

     [Authorize(Roles = StaticDetails.AdminEndUser)]  
        [BindProperties]  
        public class EditModel : PageModel  
        {  
            private readonly ApplicationDbContext _db;  
      
            public EditModel(ApplicationDbContext db)  
            {  
                _db = db;  
            }  
      
            public IEnumerable<SelectListItem> DepartmentList { get; private set; }  
      
            [BindProperty]  
            public int SelectDepartmentID { get; set; }  
            //[BindProperty]  
            //public Department Department { get; set; }  
      
            [BindProperty]  
            public ApplicationUser ApplicationUser { get; set; }  
              
            public async Task<IActionResult> OnGetAsync(string id)  
            {  
                if(id.Trim().Length==0)  
                {  
                    return NotFound();  
                }  
      
                DepartmentList = _db.Department.Select(i => new SelectListItem()  
                {  
                    Text = i.Name,  
                    Value = i.Id.ToString()  
                });  
      
                ApplicationUser = await _db.ApplicationUser.FirstOrDefaultAsync(m => m.Id == id);  
      
                if (ApplicationUser == null)  
                {  
                    return NotFound();  
                }  
      
                  
                return Page();  
            }  
      
            public async Task<IActionResult> OnPostAsync()  
            {  
                if(!ModelState.IsValid)  
                {  
                    //var department = _db.Department.Where(c => c.Id == SelectDepartmentID).FirstOrDefault();  
                    //if (department == null)  
                    //{  
                    //    //create a default department or find the default deparment from the database.  
                    //    department = new Department()  
                    //    {  
                    //        Name = "Default"  
                    //    };  
                    //}  
                    return Page();  
                }  
                else  
                {  
                    var userInDb = await _db.ApplicationUser.SingleOrDefaultAsync(u => u.Id == ApplicationUser.Id);  
                    if (userInDb == null)  
                    {  
                        return NotFound();  
                    }  
                    else  
                    {  
                        userInDb.FirstName = ApplicationUser.FirstName;  
                        userInDb.LastName = ApplicationUser.LastName;  
                        userInDb.Gender = ApplicationUser.Gender;  
                        userInDb.Genders = ApplicationUser.Genders;  
      
                        userInDb.EmployeCode = ApplicationUser.EmployeCode;  
                        userInDb.Designation = ApplicationUser.Designation;  
                        userInDb.DateOfBirth = ApplicationUser.DateOfBirth;  
                        userInDb.DateOfJoining = ApplicationUser.DateOfJoining;  
      
                        userInDb.EmergencyNo = ApplicationUser.EmergencyNo;  
                        //userInDb.AdharNo = ApplicationUser.AdharNo;  
                        userInDb.Country = ApplicationUser.Country;  
      
                        userInDb.PhoneNumber = ApplicationUser.PhoneNumber;  
                        userInDb.Address = ApplicationUser.Address;  
                        userInDb.City = ApplicationUser.City;  
                        userInDb.PostalCode = ApplicationUser.PostalCode;  
                          
                        //userInDb.Department = ApplicationUser.Department;  
                        //userInDb.DepartmentId = Convert.ToInt32(ApplicationUser.Department.Name);  
                        //DepartmentList = _db.Department.Select(i => new SelectListItem()  
                        //{  
                        //    Text = i.Name,  
                        //    Value = i.Id.ToString()  
                        //});  
                        await _db.SaveChangesAsync();  
                        return RedirectToPage("Index");  
                    }  
                }  
            }  
        }  
    

    My Edit.cshtml code

    @page  
    @model New11.Pages.Users.EditModel  
      
    <br />  
    <h2 class="text-info">Edit User</h2>  
    <br />  
    <form method="post">  
        <div class="border backgroundWhite">  
      
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
            <input asp-for="ApplicationUser.Id" hidden />  
            <input asp-for="ApplicationUser.Email" hidden />  
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.FirstName" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.FirstName" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.FirstName" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.LastName" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.LastName" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.LastName" class="text-danger"></span>  
            </div>  
      
            <div class="form-check-inline">  
                <div class="col-12">  
                    <label asp-for="ApplicationUser.Gender" class="text-info"></label>  
                </div>  
                <div class="col-8">  
                    @foreach (var gender in Model.ApplicationUser.Genders)  
                    {  
                        @*@Html.RadioButtonFor(model => model.Input.Gender, gender) @gender<br />*@  
                        <input type="radio" class="form-check-input" asp-for="ApplicationUser.Gender" value="@gender" />@gender<br />  
                    }  
                </div>  
                <span asp-validation-for="ApplicationUser.Gender" class="text-danger"></span>  
            </div>  
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.EmployeCode" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.EmployeCode" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.EmployeCode" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.Designation" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.Designation" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.Designation" class="text-danger"></span>  
            </div>  
            @*<div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.DepartmentId" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.DepartmentId" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.DepartmentId" class="text-danger"></span>  
            </div>*@  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.DateOfBirth" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.DateOfBirth" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.DateOfBirth" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.DateOfJoining" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.DateOfJoining" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.DateOfJoining" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.PhoneNumber" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.PhoneNumber" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.PhoneNumber" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.EmergencyNo" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.EmergencyNo" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.EmergencyNo" class="text-danger"></span>  
            </div>  
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label class="text-info">Department</label>  
                    </div>  
                    <div class="col-8">  
                        <select name="ApplicationUser.SelectDepartmentID" asp-items="Model.DepartmentList"></select>  
                    </div>  
                    <span asp-validation-for="ApplicationUser.DepartmentId" class="text-danger"></span>  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.Country" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.Country" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.Country" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.Email" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.Email" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.Email" class="text-danger"></span>  
            </div>  
      
      
      
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.Address" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.Address" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.Address" class="text-danger"></span>  
            </div>  
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.City" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.City" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.City" class="text-danger"></span>  
            </div>  
      
            <div class="form-group">  
                <div class="row">  
                    <div class="col-sm-2">  
                        <label asp-for="ApplicationUser.PostalCode" class="text-info"></label>  
                    </div>  
                    <div class="col-sm-5">  
                        <input asp-for="ApplicationUser.PostalCode" class="form-control" />  
                    </div>  
                </div>  
                <span asp-validation-for="ApplicationUser.PostalCode" class="text-danger"></span>  
            </div>  
      
            <div class="form-group row">  
                <div class="col-5 offset-2">  
                    <partial name="_EditAndBackToListButton" />  
                </div>  
            </div>  
        </div>  
      
    </form>  
    @section Scripts{  
        @{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
    }  
    

    and when I am Showing The User Details I Want to show associated Department Name for the Particular User insted of Department Id Do i Have to Join In LINQ ....And As I am very New in EF and LINQ can you suggest Any good Source To Learn These Things Step By Step.

    0 comments No comments

  4. Arnab 66 Reputation points
    2022-07-07T05:41:25.697+00:00

    Hi sir thanks but can you be more specific about How can I successfully Edit and save it...I am getting The list while editing from DepartmentList .But I am not Sure I am doing R8

     <div class="form-group">  
                <div class="row">  
                    <div class="col-4">  
                        <label class="text-info">Department</label>  
                    </div>  
                    <div class="col-8">  
                        <select name="ApplicationUser.SelectDepartmentID" asp-items="Model.DepartmentList"></select>  
                    </div>  
                    <span asp-validation-for="ApplicationUser.DepartmentId" class="text-danger"></span>  
                </div>  
            </div>  
      
    

    and then i am selecting The depatment In Edit page but Now i dont have a input model in Edit model class so i am am confused how to do that

    and my post method ..

     public async Task<IActionResult> OnPostAsync()  
            {  
                if(!ModelState.IsValid)  
                {  
                     
                    return Page();  
                }  
                else  
                {  
                    var department = _db.Department.Where(c => c.Id ==Department.SelectDepartmentID).FirstOrDefault();  
                    if (department == null)  
                    {  
                        //create a default department or find the default deparment from the database.  
                        department = new Department()  
                        {  
                            Name = "Default"  
                        };  
                    }  
      
                    var userInDb = await _db.ApplicationUser.SingleOrDefaultAsync(u => u.Id == ApplicationUser.Id);  
                    if (userInDb == null)  
                    {  
                        return NotFound();  
                    }  
                    else  
                    {  
                        userInDb.FirstName = ApplicationUser.FirstName;  
                        userInDb.LastName = ApplicationUser.LastName;  
                        userInDb.Gender = ApplicationUser.Gender;  
                        userInDb.Genders = ApplicationUser.Genders;  
      
                        userInDb.EmployeCode = ApplicationUser.EmployeCode;  
                        userInDb.Designation = ApplicationUser.Designation;  
                        userInDb.DateOfBirth = ApplicationUser.DateOfBirth;  
                        userInDb.DateOfJoining = ApplicationUser.DateOfJoining;  
      
                        userInDb.EmergencyNo = ApplicationUser.EmergencyNo;  
                        //userInDb.AdharNo = ApplicationUser.AdharNo;  
                        userInDb.Country = ApplicationUser.Country;  
      
                        userInDb.PhoneNumber = ApplicationUser.PhoneNumber;  
                        userInDb.Address = ApplicationUser.Address;  
                        userInDb.City = ApplicationUser.City;  
                        userInDb.PostalCode = ApplicationUser.PostalCode;  
                         
                          
                        //userInDb.Department = ApplicationUser.Department;  
                        //userInDb.DepartmentId = Convert.ToInt32(ApplicationUser.Department.Name);  
                        //DepartmentList = _db.Department.Select(i => new SelectListItem()  
                        //{  
                        //    Text = i.Name,  
                        //    Value = i.Id.ToString()  
                        //});  
                        await _db.SaveChangesAsync();  
                        return RedirectToPage("Index");  
                    }  
                }  
            }  
    

    here how do I query that and save it....Because I dont Have any input model this time....Maybe i am being very vague about that ....but struggling a lot.