0

Its so simply, sadly this new Identity system has to throw a wrench at me.

All I want to do is in my admin, create a client project that is assigned to a user. There's plenty of documentation on how to get the user to create their own stuff. But I need to have the admin create only this time.

The page loads but then on post I get this error which makes no sense in this situation based off of what I've read, "There is no ViewData item of type 'IEnumerable' that has the key 'userId'." I'm clearly not using a ViewData and it clearly says "userId" on the dropdown.

The model should validate!

MODEL

    public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ClientProject> ClientProjects { get; set; }
}

public class ClientProject
{
    public int Id { get; set; }

    [Display(Name = "Project")]
    [Required(ErrorMessage = "A project name is required.")]
    public string Name { get; set; }

    // ForeignKey => dbo.IdentityUser
    [Display(Name = "Client")]
    [Required(ErrorMessage = "Please select a client account to associate with.")]
    public virtual ApplicationUser User { get; set; }

}

CONTROLLER

        // GET: /Admin/ClientProjects/Create
    public ActionResult Create()
    {
        ViewBag.ProjectStatusId = new SelectList(Db.ProjectStatuses, "Id", "Name");
        ViewBag.Users = new SelectList(UserManager.Users.ToList(),"Id", "UserName");
        return View();
    }

    // POST: /Admin/ClientProjects/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include="Id,Name,ProjectStatusId")] ClientProject clientproject, string userId)
    {
        var client = UserManager.FindById(userId);

        if (ModelState.IsValid)
        {
            clientproject.User = client;
            Db.ClientProjects.Add(clientproject);
            await Db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        ViewBag.ProjectStatusId = new SelectList(Db.ProjectStatuses, "Id", "Name", clientproject.ProjectStatusId);
        return View(clientproject);
    }

VIEW

@Html.DropDownList("userId", (IEnumerable<SelectListItem>)ViewBag.Users, "--Select Client Account--", new { @class = "form-control" })

1 Answer 1

0

ViewData is MVC's internal representation of your view model, a key-value dictionary to which it refers when trying to bind the data you pass to the model you assign to the view. So in your case, it has no idea what userId is more than likely because your Users view model has an Id property and that's what it expects.

Basically, this MVC error means "I was looking for property [blank] in your model but couldn't find it, therefore I can't complete the task."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.