EF: Why this Model Validation error

تعرفه تبلیغات در سایت

آرشیو مطالب

امکانات وب

Vote count: 0

In ASP.NET MVC Core 1.1.1, Individual User Accounts mode, VS2017 Ver 15.3.3, I added some users using Register.cshtml. Later I created an interface to add two roles to ASPNETRoles table. Then I decided to add these users to one of the two Roles. But when I tried, for example, to add Administrator user to AdminRole, I'm getting the following validation error even though the users already have email and password into the ASPNETUsers table. I think the validation error occurs at line var result = await _userManager.AddToRoleAsync(user, "AdminRole"); of the Post action below.

Error

  1. Email is required 2. Password is required

Note: I think not related to this post - but just in case: I've slightly extended the user model by not using Email as user name; and instead adding an extra attribute UserName to the ApplicationUser.cs class and making some related changes to the Identity model as explained here. But Email is still there as a required attribute and every user does have unique email in ASPNetUsers table

LoginViewModel:

public class LoginViewModel
{
    public SelectList lstUsers { get; set; }

    [Required]
    public string SelectedUserName { get; set; } //will be used as selectedUser

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

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

Controller

....
[HttpGet]
[AllowAnonymous]
public IActionResult AddUserToRole(string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    LoginViewModel loginVM = new LoginViewModel();
    loginVM.lstUsers = new SelectList(_userManager.Users.OrderBy(u => u.UserName), "UserName", "UserName");
    return View(loginVM);
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task AddUserToRole(LoginViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        //var user = _userManager.FindByNameAsync(model.SelectedUserName); //cannot be used in AddToRoleAsync(user,"AdminRole") since FindByNameAsync returns Task
        var user = new ApplicationUser { UserName = model.SelectedUserName };
        var result = await _userManager.AddToRoleAsync(user, "AdminRole");
        if (result.Succeeded)
        {
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}
....

AddUserToRole.cshtml

@model LoginViewModel

Create a new Role.


@section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
asked 38 secs ago
nam

نویسنده : استخدام کار بازدید : 11 تاريخ : دوشنبه 27 شهريور 1396 ساعت: 1:53
برچسب‌ها :

خبرنامه

عضویت

نام کاربري :
رمز عبور :