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.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,158 questions
{count} votes

9 answers

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-06-28T06:10:40.66+00:00

    Hi @Arnab ,

    215631-image.png

    From the Register.cshtml.cs Model class, I assume you are using the RegisterModel's CategoryList property to populate the DropDownList, and after select the DropDownList item, you want to get the selected option (Department ID) via the Input Model's Department property, right? If that is the case, in the Register.cshtml page, you can use the following code to display the DropDownList:

    215632-image.png

    View the code from here: 215605-sourcecode.txt

    Then, the result is like below:

    215595-1.gif

    [Note] In the Post method, if it returns to the current page, you still need to set value to the RegisterModel's CategoryList property to populate the DropDownList.

    More detail information about using DropDownList in Razor page, see Select Lists in a Razor Pages Form.


    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,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

  2. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-06-29T01:24:16.797+00:00

    Hi @Arnab ,

    215942-image.png

    To this issue, after clicking the Register button, since there has some property invalid, it will return to the current Register page. So, as I said in the previous reply, in the Post method, you need to reset the value to the RegisterModel's DepartmentList property, and then use it to populate the DropDownList.

    Code like this:

             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();  
    
                 //...  
    
                 DepartmentList = _db.Department.Select(i => new SelectListItem()  
                 {  
                     Text = i.Name,  
                     Value = i.Id.ToString()  
                 });  
                 // If we got this far, something failed, redisplay form  
                 return Page();  
                  
         }  
    

    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,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

  3. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-07-01T00:52:42.703+00:00

    Hi @Arnab ,

    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

    Okey, I reproduced the problem. The issue relates the Input Department property, the Department Name is required:

    216599-image.png

    To solve this issue, you can remove the Department property from the InputModel model, and add a SelectDepartmentID property to store the DropDownList selected value.

            [BindProperty]  
            public int SelectDepartmentID { get; set; } //use this property to store the selected Department ID or you can change it to Department name  
            //[BindProperty]  
            //public Department Department { get; set; }  
    

    Then, use the following code to display the DropDownList:

    216666-image.png

    After that, in the OnPostAsync method, you can see the model validation is success, and then we can according to the SelectDepartmentID to find the existing Department from the database, then assign it to the ApplicationUser.

            if (ModelState.IsValid)  
            {  
                //find the existing department from the database.  
                var department = _db.Departments.Where(c => c.Id == Input.SelectDepartmentID).FirstOrDefault();  
    
                if(department == null)  
                {  
                    //create a default department or find the default deparment from the database.  
                    department = new Department()  
                    {  
                        Name = "Default"  
                    };  
                }  
    
                //// 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,  
                    Department = department  //assign the existing department to the ApplicationUser.  
                };  
    
    
                ////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)  
                {  
                       
                }  
                foreach (var error in result.Errors)  
                {  
                    ModelState.AddModelError(string.Empty, error.Description);  
                }  
            }  
            //repopulate the dropdownlist.  
            CategoryList = _db.Departments.Select(i => new SelectListItem()  
            {  
                Text = i.Name,  
                Value = i.Id.ToString()  
            });  
            // If we got this far, something failed, redisplay form  
            return Page();  
    

    The output: View the source code: 216628-registercshtmlcss.txt

    216560-1.gif


    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,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

  4. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-07-06T07:48:51.61+00:00

    Hi @Arnab ,

    One more Thing Sir can you Walk Me through How to save Department While Editing The Application User Details

    Check my precious reply, it is similar with the register page, on the Post method, you can get the select department first, then assign to the edit user's Department navigation property, then it will update the user's department.

    218072-image.png

    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 ....

    In the Register page, you have already display the Deparment name in the DropDonwlist, you can refer to it.

    To load the related entity, you can use Eager loading, refer to this tutorial: Tutorial: Read related data - ASP.NET MVC with EF Core

    Do you mean display the user's department name as the DropDownList's default selected option? If that is the case, first you can get the user's department via the Department property, then its department name or value, then when you query the Department table and get the department list (SelectListItem list), the SelectListItem has a Selected property, you can use it to set the default selected value,

    Code like this:

        public async Task OnGetAsync(string returnUrl = null)  
        {  
            //get current user information  
            var currentuser = _db.ApplicationUser.Include(c=>c.Department).FirstOrDefault();  
            //get all departments  
            CategoryList = _db.Departments.Select(i => new SelectListItem()  
            {  
                Text = i.Name,  
                Value = i.Id.ToString(),  
                Selected = i.Id == currentuser.Department.Id? true:false //based on current user's department property to set the dropDownlist default value,  
            });  
    
    
            ReturnUrl = returnUrl;  
            Input = new InputModel();  
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();  
        }  
    

    Then the result as below: after page load, the dropdownlist default selected value is current user's deparment name.

    217968-image.png

    If I misunderstand you, please let me know freely. And since this issue seems like a new question and this thread's original question has been solved, you can closed it. And to the new question, you can post a new thread about that, then it is easier for us to see it and help you solve it.


    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,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

  5. Arnab 66 Reputation points
    2022-06-28T08:20:42.39+00:00

    @Zhi Lv - MSFT sir actually i mistakenly written categoryList but it should be DepartmentList and i have CRUD for Departments alrdy.And I have saved departments in database now I want to get The Departments list from Database and then select and Save Through InputModel . As you shown i Did it but Getting An Exception..

    215656-screenshot-2022-06-28-133511.png