0

I am having a trouble fixing this error, I am trying to edit an information of a specific user but when I click the "Edit" button I am getting this error in my web browser saying:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'SanMarinoClassicWebsite.Auth.ApplicationUser', but this ViewDataDictionary instance requires a model item of type 'SanMarinoClassicWebsite.ViewModels.EditUserViewModel'.

what could I've done wrong?

Here is the action of my Admin Controller for editing the information

[Authorize(Roles ="Administrator")]
public class AdminController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public AdminController(UserManager<ApplicationUser> userManager, 
    RoleManager<IdentityRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult UserManagement()
    {
        var users = _userManager.Users;

        return View(users);
    }
    public IActionResult AddUser()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> AddUser(AddUserViewModel 
   addUserViewModel)
    {
        if (!ModelState.IsValid) return View(addUserViewModel);

        var user = new ApplicationUser()
        {
            UserName = addUserViewModel.UserName,
            Email = addUserViewModel.Email,

            City = addUserViewModel.City,
            Birthdate = addUserViewModel.Birthdate,
            Country = addUserViewModel.Country


        };

        IdentityResult result = await _userManager.CreateAsync(user, 
       addUserViewModel.Password);

        if (result.Succeeded)
        {
            return RedirectToAction("UserManagement", _userManager.Users);
        }

        foreach (IdentityError error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
        return View(addUserViewModel);
    }

    public async Task<IActionResult> EditUser(string id)
    {
        var user = await _userManager.FindByIdAsync(id);

        if (user == null)
            return RedirectToAction("UserManagement", _userManager.Users);

        return View(user);
    }

    [HttpPost]
    public async Task<IActionResult> EditUser(EditUserViewModel editUserViewModel)
    {
        var user = await _userManager.FindByIdAsync(editUserViewModel.Id);

        if (user != null)
        {
            user.Email = editUserViewModel.Email;
            user.UserName = editUserViewModel.UserName;
            user.Birthdate = editUserViewModel.Birthdate;
            user.City = editUserViewModel.City;
            user.Country = editUserViewModel.Country;

            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
                return RedirectToAction("UserManagement", 
 _userManager.Users);

            ModelState.AddModelError("", "User not updated, something went 
 wrong.");

            return View(editUserViewModel);
        }
        return RedirectToAction("UserManagement", _userManager.Users);
    }

    [HttpPost]
    public async Task<IActionResult> DeleteUser(string userId)
    {
        ApplicationUser user = await _userManager.FindByIdAsync(userId);

        if (user != null)
        {
            IdentityResult result = await _userManager.DeleteAsync(user);
            if (result.Succeeded)
                return RedirectToAction("UserManagement");
            else
                ModelState.AddModelError("", "Something went wrong while deleting this user.");
        }
        else
        {
            ModelState.AddModelError("", "This user can't be found");
        }
        return View("UserManagement", _userManager.Users);
    }

EditUserViewModel.cs

public class EditUserViewModel
{
    public string Id { get; set; }

    [Required(ErrorMessage = "Please enter the user name")]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Please enter the user email")]
    public string Email { get; set; }

    public List<string> UserClaims { get; set; }

    [Required(ErrorMessage = "Please enter the birth date")]
    [Display(Name = "Birth date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
    ApplyFormatInEditMode = true)]
    public DateTime Birthdate { get; set; }

    public string City { get; set; }

    public string Country { get; set; }
}

EditUser.cshtml

@model EditUserViewModel

<h2>Edit user</h2>

<form asp-controller="Admin" asp-action="EditUser" method="post" 
class="form-horizontal" role="form">
<h4>You can change the user details below</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>

<div class="form-group">
    <label asp-for="Id" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Id" class="form-control" />
        <span asp-validation-for="Id" class="text-danger"></span>
    </div>
</div>

<div class="form-group">
    <label asp-for="UserName" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="UserName" class="form-control" />
        <span asp-validation-for="UserName" class="text-danger"></span>
    </div>
</div>

<div class="form-group">
    <label asp-for="Email" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
</div>
<div class="form-group">
    <label asp-for="Birthdate" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Birthdate" class="form-control" />
        <span asp-validation-for="Birthdate" class="text-danger"></span>
    </div>
</div>

<div class="form-group">
    <label asp-for="City" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="City" class="form-control" />
        <span asp-validation-for="City" class="text-danger"></span>
    </div>
</div>

<div class="form-group">
    <label asp-for="Country" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Country" class="form-control" />
        <span asp-validation-for="Country" class="text-danger"></span>
    </div>
</div>


<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-primary" value="Save user" />
        <a asp-action="Index" class="btn btn-primary">Cancel</a>
    </div>
</div>
</form>

1 Answers1

0

You have a problem with you generic type.

Look at you controller.

public class AdminController : Controller
{
    // Here is the problem
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public AdminController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }
    // ...

You're using ApplicationUser to create an instance of UserManager. However, are using EditUserViewModel in your view.

You should change the type of your instance _userManager or use another type in your view.

Examples:

public class AdminController : Controller
{
    // Here is the problem
    private readonly UserManager<EditUserViewModel> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public AdminController(UserManager<EditUserViewModel> userManager, RoleManager<IdentityRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }
    // ...

Or

@model EditUserViewModel
<h2>Edit user</h2>

I hope I helped you.

andercruzbr
  • 454
  • 2
  • 10
  • I appreciate the help but ApplicationUser is just a class I have used to extend the IdentityUser, I will post the whole AdminController class, I hope you will finally solve my problem – Patrick Almario Sep 24 '18 at 17:19
  • The problem is ApplicationUser is different of EditUserViewModel. Probably the property Users in UserManager return a IEnumerable. As you create a instance of UserManager with the generic type ApplicationUser [UserManager< ApplicationUser>], Users is a IEnumerable and you view is wanting for a EditUserViewModel. – andercruzbr Sep 24 '18 at 17:28