Why the list returned from the view model to the controller is always null?

37 Views Asked by At

I'm passing a view model back from my view to the controller via a form HttpPost. However, the values type list returned are always NULL.

View model:

public class EditUserRolesViewModel
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public IList<string> UserRoles { get; set; }
    public List<IdentityRole> AllRoles { get; set; }
    public List<string> SelectedRoles { get; set; }
}

Controller (get)

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

    if (user == null)
    {
        return NotFound();
    }

    var userRoles = await _userManager.GetRolesAsync(user);
    var allRoles = _roleManager.Roles.ToList();

    var model = new EditUserRolesViewModel
    {
        UserId = Id,
        UserName = user.UserName,
        UserRoles = userRoles,
        AllRoles = allRoles
    };

    return View(model);
}

Controller (post)

// POST: User/EditRoles
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditUserRolesViewModel model) 
{ 
    if (ModelState.IsValid)  
    // ....
}

View (EDIT)

<h2>Edit User Roles</h2>
    @model EditUserRolesViewModel
    <h4>User: @Model.UserName </h4>

    <h4>Current Roles:</h4>
    
    <ul>
        @if (Model.UserRoles != null)
        {
            foreach (var role in Model.UserRoles)
            {
                <li>@role</li>
            }
        }
        else
        {
            <li>No roles assigned</li>
        }
    </ul>
    
    <h4>Select New Roles:</h4>
    
    <input type="hidden" asp-for="UserId" />
    @foreach (var role in Model.AllRoles)
    {
        <div>
            <input type="checkbox" id="@role.Name" name="SelectedRoles" value="@role.Name"
            @(Model.SelectedRoles != null && Model.SelectedRoles.Contains(role.Name) ? "checked" : "") />
            <label for="@role.Name">@role.Name</label>
        </div>
    }
    <button type="submit">Save</button>

I try to add/remove one or multiple role to a user.

0

There are 0 best solutions below