【问题标题】:.net core 5 DropDownListFor.net 核心 5 DropDownListFor
【发布时间】:2021-04-12 08:39:59
【问题描述】:

我正在向索引视图显示数据以从 viewBag 获取用户角色。它没有运行显示错误

以下代码

控制器代码

   private readonly ministrydbcContext _context;

    List<RolesTbl> allRoles = new List<RolesTbl>();


    public UserInfoController(ministrydbcContext context)
    {
        _context = context;
        allRoles = _context.RolesTbls.ToList();
        ViewBag.UserRole = new SelectList(allRoles, "RoleId", "RoleName");

    }
 public async Task<IActionResult> Index()
    {

        return View(await _context.UserInfoTbls.ToListAsync());
    }

查看代码

@model IEnumerable<CoreProj.Models.UserInfoTbl>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserEmail)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LoginName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LoginPass)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Edate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Euser)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Mdate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Muser)
        </td>
        <td>
           @Html.DropDownListFor(modelItem => item.UserRoleId, new SelectList(@ViewBag.UserRole, "RoleId", "RoleName"))


        </td>
        <td>
            <a asp-action="Edit" asp-route-id="@item.UserId">Edit</a> |
            <a asp-action="Details" asp-route-id="@item.UserId">Details</a> |
            <a asp-action="Delete" asp-route-id="@item.UserId">Delete</a>
        </td>
    </tr>

我遇到错误

ArgumentNullException:值不能为空。 (参数“项目”)

下面一行出现错误

@Html.DropDownListFor(modelItem => item.UserRoleId, new SelectList(@ViewBag.UserRole, "RoleId", "RoleName"))

【问题讨论】:

    标签: asp.net-core model-view-controller


    【解决方案1】:

    你可以像这样改变你的控制器。

    private readonly ministrydbcContext _context;
    
    public UserInfoController(ministrydbcContext context)
    {
        _context = context;
    
    }
    public async Task<IActionResult> Index()
    {
         var allRoles = await _context.RolesTbls.ToListAsync();
         ViewBag.UserRole = allRoles;
        return View(await _context.UserInfoTbls.ToListAsync());
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2017-10-23
      • 2018-06-30
      • 1970-01-01
      • 2016-06-18
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多