I am making a generic controller which receives a string containing table name and then displays list page. Display parameters such as field formatting are specified in metadata.
My plan is to use one controller, one view for list, one view for editing for ALL entities.
The view for list is like this:
@model IEnumerable<IEnumerable<object>>
<table>
@foreach (var row in Model)
{
<tr>
@foreach (var item in row)
{
<td>@Html.DisplayFor(modelItem => item)</td>
}
</tr>
}
</table>
In controller I'm retrieving List<List<object>>
(which serves as a table-like viewmodel) from database using reflection. So far so good.
These are metadata for two DbSets
:
[MetadataType(typeof(AreaMetadata))]
public partial class Area
{
class AreaMetadata
{
[Key]
public Guid Id { get; set; }
[Display(Name = "Area Name", Order = 1)]
public string Name { get; set; }
[Display(Name = "Country", Order = 2)]
public Country Country { get; set; }
}
}
[MetadataType(typeof(CountryMetadata))]
public partial class Country
{
class CountryMetadata
{
[Key]
[Display(Name = "Id")]
public Guid Id { get; set; }
[Display(Name = "Country Name", Order = 1)]
public string Name { get; set; }
[Display(Name = "Letter Code", Order = 2)]
public string LetterCode { get; set; }
[Display(Name = "Numeric Code", Order = 3)]
public int NumericCode { get; set; }
}
}
When I'm passing "Areas"
parameter to my controller, it returns a table of Areas
and their respective Countries
, and Countries
are displayed using the values of Name
field.
Experimentally I found that for non-primitive types (i.e. types that rely on connection) DisplayFor()
looks up the field with minimum Order
value in DisplayAttribute
in its metadata and uses this field as the display value for Country
.
If either Order
value or DisplayAttribute
is not specified in metadata, it throws the following exception:
'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'
So my question is: is there any other metadata attribute I should use to specify which column of particular entity should be used for its display value? I'm okay with Order
attribute, it just feels awkward to rely on the minimum value of attribute used for other fields as well.