InvalidOperationException:传递到ViewDataDictionary中的模型项的类型为

时间:2018-09-24 16:19:09

标签: asp.net-mvc asp.net-core invalidoperationexception

我在解决此错误时遇到问题,我正在尝试编辑特定用户的信息,但是当我单击“编辑”按钮时,我在Web浏览器中收到此错误:

  

InvalidOperationException:传递到ViewDataDictionary中的模型项的类型为“ SanMarinoClassicWebsite.Auth.ApplicationUser”,但是此ViewDataDictionary实例需要类型为“ SanMarinoClassicWebsite.ViewModels.EditUserViewModel”的模型项。

我做错了什么?

这是我的管理控制器用于编辑信息的操作

[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 个答案:

答案 0 :(得分:0)

您对通用类型有疑问。

看看你的控制器。

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;
    }
    // ...

您正在使用ApplicationUser创建UserManager的实例。但是,您正在视图中使用EditUserViewModel。

您应更改实例_userManager的类型或在视图中使用其他类型。

示例:

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;
    }
    // ...

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

希望我能对您有所帮助。