Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two tables user and role now while saving UserWithRole I am saving userid,roleId and date, Now on index view i want to show role name rather than role id but in UserwithRole table i am saving Role Id , but role Name is available in another Roles tables so how can i show the role name on index view rather than role id .

What I have tried:

I have no idea how to achieve it in a good way
Posted
Updated 14-Nov-19 4:08am
Comments
F-ES Sitecore 13-Nov-19 5:59am    
You do it by JOINing the two tables. How you do this depends on what database access technology you are using (aso.net, entity framework, nHibernate etc) so without knowing that we can't give specific advice.
Malikdanish 13-Nov-19 23:22pm    
I am using entity framework . private DatabaseContext db = new DatabaseContext();

// GET: UserRoles
public ActionResult Index()
{

return View(db.UserRoles.ToList());
}

1 solution

Make sure you have a navigation property[^] set up on your UserRole entity. Then you simply need to Include the role, and use the navigation property to display the name.

Entity:
C#
public class UserRole
{
    public int UserId { get; set; }
    public User User { get; set; }
    
    public int RoleId { get; set; }
    public Role Role { get; set; }
}
Controller:
C#
public ActionResult Index()
{
    return View(db.UserRoles.Include(ur => ur.User).Include(ur => ur.Role).ToList());
}
View:
Razor
@foreach (UserRole item in Model)
{
    <p>User @item.User.Name is in role @item.Role.Name</p>
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900