c# - ArgumentNullException : Value cannot be null.(参数 'items')异常

标签 c# asp.net-core .net-core identity asp.net-core-identity

我使用身份验证创建了 asp.net 核心项目 -> 个人用户帐户。我创建了所有角色并授权了他们的页面。现在我正在创建用户页面。我想创建一个包含已创建角色的下拉列表。即使在 .cshtml 文件上有 ViewData,我也会得到空参数异常。我的代码如下所示。

using Project.Data;
using Project.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Project.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
        private UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;
        public string ReturnUrl { get; set; }


        public AdminController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            this._userManager = userManager;
            this._roleManager = roleManager;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public IActionResult GetAllUsers()
        {
            var users = _userManager.Users;
            return View(users);
        }

       public void OnGet()
        {
           ViewData["roles"] = _roleManager.Roles.ToList();
        }

        public ViewResult Create() => View();

        [HttpPost]
        public async Task<IActionResult> Create(User user)
        {
            var role = _roleManager.FindByIdAsync(user.UserRole).Result;
           

            if (ModelState.IsValid)
            {
                ApplicationUser appUser = new ApplicationUser
                {
                    UserName = user.UserName,
                    Email = user.Email,
                    PhoneNumber = user.TelephoneNumber,
                    FirstName = user.FirstName,
                    LastName = user.LasttName,
                    Address = user.Address,
                    UserPIN = user.UserPIN
                };

                IdentityResult result = await _userManager.CreateAsync(appUser, user.Password);
                if (result.Succeeded)
                {
                    var currentUser = _userManager.FindByIdAsync(appUser.Id);
                    await _userManager.AddToRoleAsync(appUser, role.Name);

                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                        ModelState.AddModelError("", error.Description);
                }
            }
            return View(user);
        }

     
    }
}





@model User

    @{
        var roles = (IEnumerable<Microsoft.AspNetCore.Identity.IdentityRole>)ViewData["roles"];
    }

    <h1 class="bg-info text-white">Create User</h1>
    <a asp-action="Index" class="btn btn-secondary">Back</a>
    <div asp-validation-summary="All" class="text-danger"></div>

    <form method="post">
        <div class="form-group">
            <label asp-for="FirstName"> First name</label>
            <input asp-for="FirstName" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="LasttName"> Last name</label>
            <input asp-for="LasttName" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="UserName"> Username</label>
            <input asp-for="UserName" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="UserPIN">User PIN</label>
            <input asp-for="UserPIN" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="Email"></label>
            <input asp-for="Email" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="TelephoneNumber"></label>
            <input asp-for="TelephoneNumber" class="form-control" />
        </div>
          <div class="form-group">
            <label asp-for="UserRole">Role</label>
            <select asp-for="UserRole" class="form-control" asp-items='new SelectList(roles,"Id","Name")'></select>
        </div>
        <div class="form-group">
            <label asp-for="Address">Address</label>
            <input asp-for="Address" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="Password"></label>
            <input asp-for="Password" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="ConfirmPassword"></label>
            <input asp-for="ConfirmPassword" class="form-control" />
        </div>
        <button type="submit" class="btn btn-primary">Create</button>
    </form>







    using Microsoft.AspNetCore.Identity;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Project.Models
    {
        public class User
        {
            
            [Required]
            [EmailAddress]
            [Display(Name = "Email")]
            public string Email { get; set; }
    
            [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }
    
            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }
    
           // [Required]
            public string UserRole { get; set; }
    
            [Required]
            public string FirstName { get; set; }
    
            [Required]
            public string LasttName { get; set; }
    
            [Required]
            public string Address { get; set; }
    
            [Required]
            [StringLength(50, MinimumLength = 10,
            ErrorMessage = "User name must have min length of 6 and max Length of 50")]
            public string UserName { get; set; }
    
            [Required]
            [StringLength(10, MinimumLength = 10,
            ErrorMessage = "User PIN must be 10 characters long")]
            public string UserPIN { get; set; }
    
            [Required]
            [StringLength(10, MinimumLength = 10,
            ErrorMessage = "Telephone number must be 10 characters long")]
            public string TelephoneNumber { get; set; }
    
            
        }
    }

最佳答案

为什么你不改变你的行为:

 
        public ActionResult Create()
       {
        var roles = _roleManager.Roles.ToList();
        ViewBag.Roles= new SelectList(roles,"Id","Name");
        return View( new User());
        }

并查看

 <select asp-for="UserRole" class="form-control" asp-items="@ViewBag.Roles"></select>

关于c# - ArgumentNullException : Value cannot be null.(参数 'items')异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66819228/

相关文章:

c# - RavenDB 排序方式

c# - 如何使用C#设置基于GridView的Excel图表区域范围?

linux - Manjaro/Arch Linux - 如何信任我的 Asp Net Dev 证书?

.net-core - ReSharper 2018.1.2 NUnit TestCaseSource (.NET Core/VS2017)

tfs - vs2015不断添加project.lock.json到tfs

c# - ASP.NET 请求验证程序允许的脚本

c# - 如何设置依赖属性值?

F#、Visual Studio 2017 和 dotnet new

c# - ASP.NET Core 禁用响应缓冲

c# - .net core 路由,用通用路由了解什么应用程序调用