I have a following problem. I have a class in the entity framework model that has properties e.g.:
class Company{
public string Name {get; set};
public string Address {get; set};
public string Email{get; set};
public string WebSite {get; set};
}
I have configuration in database that defines whether or not some field should be shown or not e.g:
- Name: show
- Address: show
- Email: hide
- Website: hide
This is dynamic and all fields are referenced by name.
When I display object in view. It would be nice to convert somehow a single object to some dictionary where key will be property name and value will be property value so I can check for every field by name whether it should be shown or not (maybe in some for-each loop) e.g.:
CompanyDetails.cshtml
<h2>Company Details</h2>
@foreach(var property in modelDictionary.Keys){
@if(IsVisible(property))
@Html.Raw( modelDictionary[property] )
}
What is the best way to convert a single object from entity framework model to dictionary of properties? Should I convert it from object to dictionary in the controller action or use model metadata somehow in the view?
I can use reflection on the Company class and find all properties in the class so I can populate dictionary, but this looks like too old-school solution, so I wander is there any better way to do this?
Thanks
You could use a
RouteValueDictionarywhich allows you to convert an object into a dictionary:and in the view: