You need to enable JavaScript to run this app. ASP.NET Core 5视图传组合模型 Post验证失败IdentityRoles为空如何解决
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 5视图传组合模型 Post验证失败IdentityRoles为空如何解决

问题原因

HttpPost请求验证失败重新渲染视图时,你没有为视图模型的IdentityRoles字段重新赋值,也没有将用户提交的模型数据传回视图,导致视图拿到的Model为空,遍历IdentityRoles时自然抛出空引用异常。

解决步骤

1. 修正HttpPost方法的返回逻辑

在返回视图前,重新加载角色列表赋值给视图模型,再将完整的视图模型传入View方法,同时可以删除原有冗余的对象初始化代码:

[HttpPost]
public async Task<IActionResult> UserRegistration(RegistrationViewModel registrationModel)
{
    if (ModelState.IsValid)
    {
        var user = new IdentityUser()
        {
            UserName = registrationModel.Registermodel.Email,
            Email = registrationModel.Registermodel.Email
        };

        var result = await userManager.CreateAsync(user, registrationModel.Registermodel.Password);

        if (result.Succeeded)
        {
            return RedirectToAction("Index", "Home");
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
    }

    // 验证失败时重新加载角色列表,保留用户已填写的表单数据
    registrationModel.IdentityRoles = authenticationService.GetRoles();
    return View(registrationModel);
}

2. 可选:抽取公共方法避免代码冗余

可以把加载角色的逻辑抽成私有方法,统一给HttpGet和HttpPost调用,后续修改角色加载逻辑时只需改一处:

private void LoadRolesForViewModel(RegistrationViewModel viewModel)
{
    viewModel.IdentityRoles = authenticationService.GetRoles();
}

// HttpGet方法调用
[HttpGet]
public IActionResult UserRegistration()
{
    RegistrationViewModel Registration = new RegistrationViewModel();
    LoadRolesForViewModel(Registration);
    return View(Registration);
}

// HttpPost验证失败时调用
LoadRolesForViewModel(registrationModel);
return View(registrationModel);

3. 可选:增加视图空判断防护

可以在视图遍历角色前先判空,避免极端场景下的报错:

@if (Model.IdentityRoles?.Any() == true)
{
    foreach (var role in Model.IdentityRoles)
    {
        <nav class="d-inline-block p-2">
            @Html.RadioButtonFor(m => m.Registermodel.RoleId, role.Id)@role.Name
        </nav>
    }
}

内容的提问来源于stack exchange,提问作者user13904377

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 17:39:03