I have an MVC 4 blogging application and I am trying to add an Admin Panel that allows an admin to Edit/Delete Accounts that have registered. I have the view and models in place, but I cannot figure out why my models are not being communicated correctly. Here is my code:
First I have a simple ViewModel for my Admin panel. It just contains a list that will hold all the registered users of the web app.
public class AdminViewModel
{
public List<User> UserList { get; set; }
}
Here is my controller that fetches the users as a list and sends them to the Admin view
[HttpGet]
public ActionResult Admin()
{
AdminViewModel avm = new AdminViewModel();
avm.UserList = Db.Users.ToList();
return View(avm);
}
Then here is my view that displays all the account information, has a Delete link to remove a user, and some checkboxes to change the abilities of the user.
@using cpts483.Models.ViewModels
@using cpts483.Models
@model AdminViewModel
<h1>Admin Control Panel</h1>
@using (@Html.BeginForm("UpdateUsers", "Home", FormMethod.Post))
{
<table>
<tr>
<th></th>
<th>Id</th>
<th>Email</th>
<th>First Name</th>
<th>Last Name</th>
<th>IsAdmin</th>
<th>CanWriteArticles</th>
</tr>
<tbody>
@foreach (User u in Model.UserList)
{
<tr>
<td>
@Html.ActionLink("Delete", "DeleteUser", new {id = u.Id})
</td>
<td>@u.Id</td>
<td>@u.Email</td>
<td>@u.FirstName</td>
<td>@u.LastName</td>
<td>
@Html.CheckBoxFor(m => m.UserList.Find(us => us.Id == u.Id).IsAdmin)
</td>
<td>
@Html.CheckBoxFor(m => m.UserList.Find(us => us.Id == u.Id).CanWriteArticles)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Save Changes" id="update-users-btn" />
}
Now, I thought this would bind my AdminViewModel.UserList
to the checkboxes in the DOM and then when he form is submitted, that same AdminViewModel would get sent to my post back handler with the updated data. However, instead of that, the handler below has an AdminViewModel parameter that is null every time. What am I doing wrong here?
[HttpPost]
public ActionResult UpdateUsers(AdminViewModel avm) // THIS avm IS ALWAYS NULL
{
foreach (User u in avm.UserList)
{
Db.Users.Attach(u);
}
Db.SaveChanges();
return RedirectToAction("Admin");
}