Search code examples
c#asp.netcontrolleractionresult

How to return an empty list in View in ASP.NET


I want to show all users with a specified role name. What I am doing is just specify a role name in the View. If this name exists then show all the related users (this works now), or display nothing (Exceptions arose here). Here is my code in controller:

public ActionResult ViewUser(string roleName)
    {       
        var UsersContext = new ApplicationDbContext();
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
        if (roleManager.RoleExists(roleName))
        {
            var role = roleManager.FindByName(roleName).Users.First();
            var usersInRole = UsersContext.Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
            return View(usersInRole);
        }
        else
        {
            return View();
        }

    }

Here is the code with a non-existing role name called "Worker" in View:

@Html.ActionLink("Manage User", "ViewUser", "Home", new { @roleName="Worker"}, new { style = "color:white" })

The following screenshot is the result when I specify "Customer" which exists in database as the role name. If I specify another non-existing name, the result should have contained no user list. enter image description here


Solution

  • Assumed that you're returning User entity instance from usersInRole collection inside if block, you can restructure if block to automatically return empty List<User> collection if no conditions are met (also added null checking for FindByName() method):

    public ActionResult ViewUser(string roleName)
    {       
        var UsersContext = new ApplicationDbContext();
        var usersInRole = new List<User>(); // assign instance before if conditions
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    
        if (roleManager.RoleExists(roleName))
        {
            // change to FirstOrDefault is more recommended
            var role = roleManager.FindByName(roleName).Users.FirstOrDefault();
            if (role != null)
            {
                usersInRole = UsersContext.Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
            }
        }
    
        return View(usersInRole);
    }
    

    Or simply returning empty list in else block:

    var emptyList = new List<User>();
    return View(emptyList);
    

    Additionally, make sure that you're using @model User to bind it in view page.