【发布时间】:2021-06-08 13:26:53
【问题描述】:
我有一个视图模型,用于授予和删除管理员权限。
包括以下内容
namespace PenedaVes.ViewModels
{
public class RootViewModel
{
public List<UserBox> UserBoxesList;
public string TestAtributte { get; set; }
}
public class UserBox
{
public string UserId { get; set; }
public string Username { get; set; }
public bool IsChecked { get; set; }
}
}
Test 属性仅用于调试以检查整个视图模型是否为 null 或者它只是列表。 然后我有一个控制器,叫做 Panel 控制器,它有一个 get 和一个 post 方法:
public async Task<IActionResult> Index()
{
List<ApplicationUser> users = await _userManager.Users.ToListAsync();
List<UserBox> userBoxes = new List<UserBox>();
foreach(ApplicationUser user in users)
{
if (await _userManager.IsInRoleAsync(user, "Root")) continue;
UserBox ub = new UserBox
{
UserId = user.Id,
Username = user.UserName,
IsChecked = await _userManager.IsInRoleAsync(user, "Admin")
};
userBoxes.Add(ub);
}
RootViewModel vm = new RootViewModel {UserBoxesList = userBoxes, tipo = "Hello"};
return View(vm);
}
[HttpPost]
public async Task<IActionResult> ChangePermissions(RootViewModel vm)
{
Console.WriteLine(vm.Test)
Console.WriteLine(vm.UserBoxerList.Count)
}
最后用到的视图如下:
@model RootViewModel
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Admin permissions pannel</h1>
<form asp-controller="Panel" asp-action="ChangePermissions" method="post">
<table>
<h3> User List</h3>
@for (int i = 0; i < Model.UserBoxesList.Count; i++)
{
@if (i % 3 == 0)
{
@:<tr></tr>
}
<td>
@Html.CheckBoxFor(model => model.UserBoxesList[i].IsChecked)
<label> @Model.UserBoxesList[i].Username</label>
@Html.HiddenFor(model => model.UserBoxesList[i].Username)
@Html.HiddenFor(model => model.UserBoxesList[i].UserId)
</td>
}
</table>
<div class="form-group form-check">
<label class="control-label">
<input class="form-check-input" asp-for="@Model.TestAtributte" /> This is a test attribute
</label>
</div>
<input type="submit" value="Change" class="btn btn-primary" />
</form>
每当我提交此表单时,TestAtribute 总是带有新值,但是,列表作为空值出现并抛出 NullReferenceException,这让我感到困惑,因为它在视图中呈现时不为空。
任何帮助将不胜感激。
【问题讨论】:
标签: c# asp.net-core model-view-controller