How to reference field value in ViewData.Model by the fields string name
I have a FormViewModel that includes a LINQ to SQL resultset, and a List object.
The resultset is a set of all possible field values that can be displayed in the view.
These are Model.AllFields.Field1, Model.AllFields.Field2, ...
There is a List (Model.UserFields) that contains the string names of a subset of the fields in AllFields that a particular user wants to display.
The List contains (Model.UserFields.ItemSource) field names "Field3", "Field16", ...
How can I accomplish this, where item.ItemSource is the string fieldname: (pseudo VB)
<%For Each item In Model.UserFields%>
<td><%=Html.Encode(Model.AllFields(item.ItemSource))%></td>
<%Next item%>
I realize I could change the model to accomplish this in a different manner, but is there a way to accomplish this via an "indirec开发者_如何转开发t" reference like above?
Thanks
One easy way (not necessarily the fastest, but probably fast enough for almost all use cases) is to use reflection. My VB is a bit rusty, but the code is something like this:
<%For Each item In Model.UserFields%>
<td><%=Html.Encode(Model.AllFields.GetType().GetProperty(item.ItemSource).GetValue(Model.AllFields, Nothing).ToString())%></td>
<%Next item%>
精彩评论