tags:

views:

66

answers:

1

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 "indirect" reference like above?

Thanks

A: 

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%>
Justin Grant
Works Great. Is there a way to handle null values in the GetValue?
SY
There's a few ways to do it, but at this point the complexity of this code is probably more than you want inline. I'd suggest creating a helper method in your view page (e.g. in a runat=server script block) which accepts the field name and returns the string value (or empty string if the value is null).
Justin Grant
Thanks for your help!
SY