Fetching data from database and populating a dropdownlist from a List<object> in MVC

I have a Controller to load the view:

public ActionResult AssignRole(long id = 0)
    {
        user UserModel = new user();
        int UserId = Convert.ToInt32(id);
        IList<user> Users = new List<user>();
        var query = from Role in db.Roles
                    join UserRole in db.UserRoles on Role.ID equals UserRole.RoleID
                    join user in db.users on UserRole.UserID equals user.id
                    where UserRole.UserID == UserId
                    select new { RoleName  = Role.RoleName, email = user.email, UserId = user.id };



        var userss = query.ToList();
        foreach(var userList in userss)
        {
            Users.Add(new user()
                {
                    id = userList.UserId,
                    email = userList.email,
                    RoleName = userList.RoleName
                });
        }

        LoadRoles(Users);
        return View(Users);
    }

public void LoadRoles(IList<user> model)
    {

        var Roles = db.Roles.AsQueryable<Role>().Select(x => new SelectListItem()
        {

            Text = x.RoleName,
            Value = SqlFunctions.StringConvert((double) x.ID)
        }).ToList();

        var UserModel = new user()
        {
            Roles = Roles.ToList()
        };

    }

I am able to get other values from the LINQ in the first part of view but unable to populate the dropdownlist.

How can I populate the dropdownlist. I have tried so much but still no luck. Any urgent help will be appreciated.

Here is a similar post where I explain How I use ajax to do what your looking to do:

http://forums.asp.net/t/2020174.aspx?Populate+dropdown+with+data

Hi naeemmalik87,

Thanks for your post.

You can try to get all the roles from the database using "GetAllRoles()" method into SelectList  and sets into the ViewBag. The same is being populated as DropDown into the view.

More information:

http://www.dotnetfunda.com/articles/show/2648/working-with-roles-in-aspnet-mvc-4

Hope this can be helpful.

Best Regards,

Eileen

Leave a Reply