2
Answers

Fetching data from database and populating a dropdownlist fr

Naeem Awan

Naeem Awan

9y
750
1
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.

 
Answers (2)