1

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!

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Jonas Willander
  • 432
  • 3
  • 9
  • 29
  • You are not the first I have seen doing this and I am very curious to why I am seeing more devs doing this. Why are you using the ViewBag instead of creating a model to hand to the view? With that said, that is actually part of your issue. The ViewBag is NOT your model (in your view) so your model will be null – Jason H May 21 '17 at 15:46
  • @JasonH Thank you for your response. The mail problem is I'am new to MVC and I don't know what I'am doing. – Jonas Willander May 21 '17 at 15:55
  • your ViewModel you have, you should have it include the data you need to populate the dropdown list then hand it down with your GET so that the View is populated. Then Google how to populate a DropdownList from a ViewModel – Jason H May 21 '17 at 15:57
  • @JasonH Do you mean popup Dropdownlist in my Register.cshtml and retrieving its selected value in the Reginster action method ....? I have googled many hours but could not understand how to do, That's Why I'am here to get help. Belive me I tried in hours without seccess. – Jonas Willander May 21 '17 at 16:10
  • OK give me a moment to write up an example – Jason H May 21 '17 at 16:11

1 Answers1

1

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>
Ashiquzzaman
  • 5,129
  • 3
  • 27
  • 38
  • Thank you for your response, I get error in View..SelectList((IEnumerable) "Using the generic type IEnumerable Requires 1 type arguments....." – Jonas Willander May 21 '17 at 16:45
  • @Ashinquzzaman , But this error is in View and stile the same error afte rI added .Tostring() in action method. ..SelectList((IEnumerable) "Using the generic type IEnumerable Requires 1 type arguments..... – Jonas Willander May 21 '17 at 16:53
  • @Ashinquzzaman I think I have to put something in IEnum.. – Jonas Willander May 21 '17 at 16:54
  • I think you have reference `System.Collections.Generic` in your view but `SelectList` requires `System.Collections.IEnumerable` try it with the explicit namespace : `new SelectList((System.Collections.IEnumerable) ViewBag.DeptList, "Value", "Text",Model.DepartmentId)` – Ashiquzzaman May 21 '17 at 16:56
  • @Ashinquzzaman thank you , but now it's givs me another error .. Object reference has not been specified to an instance of an object. – Jonas Willander May 21 '17 at 17:05
  • @Ashinquzzaman now I get this error.. Value must not be null , in View page – Jonas Willander May 21 '17 at 17:10
  • your model public int DepartmentId { get; set; } so DepartmentId is required field. – Ashiquzzaman May 21 '17 at 17:14
  • @Ashinquzzaman , In my Class or in RegisterViewModel? I have deleted Requriment in RegisterViewModel and stil the same error., but Do I need update database? – Jonas Willander May 21 '17 at 17:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/144844/discussion-between-jonas-willander-and-ashiquzzaman). – Jonas Willander May 22 '17 at 13:47