0

I have two tables: Users (user_id, name) and Records (record_id, record_time, user1_id, user2_id). So for each record there should be two users. I want to list records and display user names of user 1 and user 2. Now default View structure can display only one related user name by id.

How do I retrieve the name of second user of the record?

INDEX action

public ActionResult Index()
    {
        var records = db.Records.Include(r => r.User);
        return View(records.ToList());
    }

INDEX view

<table class="table">
<tr>        
    <th>
        @Html.DisplayNameFor(model => model.record_time)
    </th>               
    <th>
        @Html.DisplayNameFor(model => model.User.name)
    </th>        
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.record_time)
    </td>        
    <td>
        @Html.DisplayFor(modelItem => item.User.name)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.record_id }) |
        @Html.ActionLink("Details", "Details", new { id=item.record_id }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.record_id })
    </td>
</tr>
}

</table>
  • You're looping through the list in the view, so in theory you should be showing both users right now... assuming there are two results? – Luke Oct 15 '16 at 10:54
  • You need to show the model for `Record` - it should have navigation properties for `user1` and `user2` –  Oct 15 '16 at 10:59
  • 1
    Then `@Html.DisplayFor(m => item.User.name)` and `@Html.DisplayFor(m => item.User1.name)` should work fine (you may need `.Include(r => r.User1)` as well) –  Oct 15 '16 at 11:01
  • 1
    Basically you need `@Html.DropDowmListFor(m => m.SelectedUser, Model.UserList)` where you model contains properties `int SelectedUser` and `IEnumerable` and you populate the `SelectList` in the controller using (say) `model.UserList = new SelectList(db.Users, "ID", "Name");` - refer [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for more detail. If your having problems, then you need to ask a new question with the relevant code and a description of what's not working –  Oct 16 '16 at 07:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125826/discussion-between-stephen-muecke-and-swa). –  Oct 16 '16 at 07:50

1 Answers1

0

The mappings are incorrect, you mapped only one user. You need to map both users on different navigation properties.

class Record 
{
    public User User1 {get; set;}
    public User User2 {get; set;}
}
Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73