I would like to have an empty table on my View, and fill it using AJAX based on some dropdown list selection by the user. My model contains data for the dropdown list. As table header is not changing, I want it to be statically on the View. I wonder what is a good way to pass to the View column names to be used in @Html.DisplayNameFor()
. Of course, I can pass one record and retrieve the name from it, e.g.
@Html.DisplayNameFor(model => model.Employees[0].LastName)
But it seems to me awkward. I would like to avoid sending data to the View, as the table initially is empty, so the data itself is not used. Could you please suggest a more elegant way? Thanks.
I came to a solution that works, though I am not sure that it is the best solution possible. First, to my ViewModel (which is EmployeesViewModel) I added a member of type EmployeeViewModel:
public class EmployeeViewModel
{
public int Id { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string Gender { get; set; }
public int? Salary { get; set; }
public int? DepartmentId { get; set; }
[Display(Name = "Department Name")]
public string DepartmentName { get; set; }
}
public class EmployeesViewModel
{
public SelectList Departments { get; set; }
public EmployeeViewModel EmployeeColumnNamesRetriever { get; set; }
}
In the controller, I instantiate my Departments, but not EmployeeColumnNamesRetriever, as I need it only to get its metadata:
EmployeesViewModel employees = new EmployeesViewModel
{
Departments = new SelectList(db.Departments, "Id", "Name"),
};
And in the View:
<th>
@Html.DisplayNameFor(model => model.EmployeeColumnNamesRetriever.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeColumnNamesRetriever.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeColumnNamesRetriever.Gender)
</th>
EmployeeColumnNamesRetriever is null, but it does not matter. If somebody can suggest something nicer, I would be grateful.