我正在创建一个编辑用户页面,它将修改web应用程序中用户的现有角色名。但是,根据POST请求,在包含表单中的值(使用断点检查此值)后,Edit的视图模型变为null。
然后我在Visual中得到一条提示消息,上面写着:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.AspNetCore.Mvc.Razor.RazorPage\<TModel\>.Model.get returned null.
UserController.cs
[HttpPost]
public async Task<IActionResult> Edit(IFormCollection formCollection)
{
try
{
await _userControllerService.EditAzureUser(formCollection);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
UserControllerService.cs
public async Task EditAzureUser(IFormCollection formCollection)
{
string id = formCollection["User.PrincipalId"];
string appRoleId = formCollection["User.AppRoleId"];
//Edit logic here
}
Edit.cshtml
@model CreateUserViewModel
@{
ViewData\["Title"\] = "Edit User";
}
<label asp-for="User.PrincipalDisplayName" class="col-form-label">Name: </label>
<input asp-for="User.PrincipalDisplayName" value="@Model.User.PrincipalDisplayName" readonly class="form-control"/>
<label class="col-form-label">Role: </label>
<select asp-for="User.AppRoleName" title="Select Role" required class="form-control" style="margin-bottom: 1rem"/>
@{
foreach(var role in AppRole.Roles)
{
if(Model.User.AppRoleName == role)
{
<option value="@role" selected>@role</option>
} else
{
<option value="@role">@role</option>
}
}
}
<input type="hidden" asp-for="User.AppRoleId"/>
<input type="button" value="Cancel" class="btn btn-secondary btn-sm" onclick="goBack()" />
<input type="submit" class="btn btn-info btn-sm" />
发布于 2022-10-28 14:23:06
POST方法不会将模型返回到视图,但是视图需要一个非空CreateUserViewModel
,它在标记中使用。我猜这就是为什么你要拿到NRE。
然而,如果文章是成功的,你为什么要回到编辑页面呢?或者将它们发送到另一个页面(如果这是一个管理工具,则通常是一个用户列表,或者“如果是针对用户自己的话)”,或者在这个视图中修改Razor以显示一条消息表明编辑是成功的。不管怎样,您不需要模型。
https://stackoverflow.com/questions/74235705
复制相似问题