Currently in MVC, we have to define columns manually whenever we want to list out items:
<tr>
<td>
@Model.Name
</td>
<td>
@Model.Age
</td>
<td>
@Model.Gender
</td>
</tr>
What I want to do however, is to have a ViewModel where we specify which columns should be used, something like:
var model = new PersonViewModel(
// List of persons
CollectionOfPersons,
// List of columns that we want to display
new Expression<Func<Person, object>>[]
{
x => x.Name,
x => x.Age,
x => x.Gender
});
Then in our view, all I need to do is:
<tr>
// Model.Predicates is our ViewModel's selected columns
@foreach(var predicate in Model.Predicates)
{
<td>
// This would basically loop each pre-defined lambda expression in our ViewModel
@Html.DisplayFor(predicate)
</td>
}
</tr>
I have to admit I have a very weak understanding of expressions, and I have so far been unsuccessful in looking for information. Does anyone have any idea if this is possible to do?
Seems like the html helpers don’t work like that (passing in the expression as a variable). The compiler explicitly needs an expression to be able to determine the TModel and TResult types to be able to work.