0
votes

I am showing data from to Index view to get user roles from viewBag. it is not running showing error

with following code

Controller Code

   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());
    }

View Code

@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>

I am getting error

ArgumentNullException: Value cannot be null. (Parameter 'items')

error is coming on below line

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

1

1 Answers

1
votes

You can change your controller like this.

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());
}