locked
How to show the inner join column in index razor page? RRS feed

  • Question

  • User521171331 posted

    Hi,

    This is my Razor page code. 

    @model IEnumerable<ContosoUniversity.Models.Attendance>
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EmployeeID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.WorkDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.WorkHour)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.WorkDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.WorkHour)
            </td>
    
    
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
                @Html.ActionLink("Details", "Details", new { id=item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.Id })
            </td>
        </tr>
    }
    
    </table>
    

    Now, it is showing the foreign key employee ID. But I need to show employee name instead. In my controller, my ActionResult Index method code is below but not working.

    public ActionResult Index(int? SelectedEmployee)
            {
                var employees = db.Employees.OrderBy(q => q.Name).ToList();
                ViewBag.SelectedEmployee = new SelectList(employees, "EmployeeID", "Name", SelectedEmployee);
                int employeeID = SelectedEmployee.GetValueOrDefault();
    
                IQueryable<Attendance> attendances = db.Attendances
                    .Where(c => !SelectedEmployee.HasValue || c.EmployeeID == employeeID)
                    .OrderBy(d => d.Id)
                    .Include(d => d.Employee);
                
                return View(attendances.ToList());
    
            }

    Sunday, December 3, 2017 4:21 AM

All replies

  • User1400794712 posted

    Hi ngaisteve1,

    According to your last post, I find there is Employee property in Attendance entity. Then you can get the employee name by this property. Please follow my code below:

    <th>
        @Html.DisplayNameFor(model => model.Employee.Name )
    </th>
    //....
    <td>
        @Html.DisplayFor(modelItem => item.Employee.Name)
    </td><sub></sub><sup></sup>

    Best Regards,
    Daisy

    Monday, December 4, 2017 4:22 AM