Search code examples
asp.net-mvcdropdownselectlistitem

Adding a dropdown of Departments in the in Register.cshtml and retrieving its selected value in the Reginster action method


In my Asp:Net MVC project I want to add departments to the Registerform. When I try to register a user I get this error

There is no ViewData item of type 'IEnumerable' that has the key 'DepartmentId'.

and I think it's something to do with my Register action. This is my Department class in my Model

public class Department
  {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int DepartmentId { get; set; }
        [Required]
        [MaxLength(50)]
        public string DepartmentName { get; set; }
    }

Then I added this two properity to RegisterViewModel

public int DepartmentId { get; set; }
    public Department Department { get; set; }

Looks like this below..

public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }


        [Required]
        public string FirstName { get; set; }


        [ForeignKey("Department")]
        public int DepartmentId { get; set; }
        public Department Department { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} 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; }
    }

Then In my Register action I dont know how to code it .. tried many kind of codes but don't know how to do it.

// Probably it's here the very problem , i think.

// GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
           // Here inside.. I don't know how to do... ;)
            ViewBag.DepartmentId = new SelectList(?????, "DepartmentId", "DepartmentName");
        Or maybe:
            ViewBag.DepartmentId = new IEnumerable<SelectListItem> .....;


            return View();
        }

        // And this is what my Register looks like
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {FirstName = model.FirstName, DepartmentId = model.DepartmentId, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
......

And RegisterView


    @model PersonRegister.Models.RegisterViewModel
        ....
        <div class="form-group">
                @Html.LabelFor(m => m.DepartmentId, new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.DropDownList("DepartmentId", null, htmlAttributes: new { @class = "form-control" })
                </div>
            </div>

.....
... and here rest of view such as... email.....

Thank you in advance!


Solution

  • Example:

      [AllowAnonymous]
        public ActionResult Register()
        {
    
            ViewBag.DeptList = _context.Departments
                                      .select(s=> new SelectListItem
                                      {
                                       Value=s.DepartmentId.ToString(),
                                       Text=s.DepartmentName
                                      }).ToList();//select data from determent table 
    
            return View();
        }
    

    View

      @model PersonRegister.Models.RegisterViewModel
            ....
            <div class="form-group">
                    @Html.LabelFor(m => m.DepartmentId, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                     @Html.DropDownListFor(m => m.DepartmentId , new SelectList((IEnumerable)ViewBag.DeptList,"Value","Text",Model.DepartmentId ), new { @class = "form-control" })
                    </div>
                </div>
    

    OR

    public class RegisterViewModel
        {
             Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    
    
        [Required]
        public string FirstName { get; set; }
    
        public int? DepartmentId { get; set; }   
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} 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; }
            [Ignore]
            public List<SelectListItem> DepartmentList {get;set;}
        }
    
      [AllowAnonymous]
        public ActionResult Register()
        {
          var model= new RegisterViewModel();
            model.DepartmentList = _context.Departments
                                      .select(s=> new SelectListItem
                                      {
                                       Value=s.DepartmentId.ToString(),
                                       Text=s.DepartmentName
                                      }).ToList();//select data from determent table 
    
            return View(model);
        }
    

    View

      @model PersonRegister.Models.RegisterViewModel
            ....
            <div class="form-group">
                    @Html.LabelFor(m => m.DepartmentId, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                     @Html.DropDownListFor(m => m.DepartmentId ,Model.DepartmentList,"--Select--" ,new { @class = "form-control" })
                    </div>
                </div>